mongo-locks 3.0.2 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,6 +5,10 @@ Simple and bountiful locks to avoid doing the same operation multiple times
5
5
  The purpose of this package is simply to avoid doing the same thing twice at the same time
6
6
  and make your system a bit more user-proof.
7
7
 
8
+ ```bash
9
+ npm install mongo-locks
10
+ ```
11
+
8
12
  ```ts
9
13
  import { LockManager } from "mongo-locks";
10
14
  import { MongoClient } from "mongodb";
@@ -13,7 +17,7 @@ const client = new MongoClient("mongodb://localhost:27017");
13
17
  const lockManager = new LockManager(client.db().collection("mongo-locks"));
14
18
 
15
19
  async function doStuff() {
16
- await using lock = lockManager.lock("unique string key");
20
+ await using lock = await lockManager.lock("unique string key");
17
21
 
18
22
  if (!lock) {
19
23
  console.log("Lock already taken");
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,113 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { ObjectId } from "mongodb";
11
+ export class MongoLocksError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ }
15
+ }
16
+ const makeKey = (key) => {
17
+ // Arrays mess up the unique MongoDB indexes
18
+ return Array.isArray(key) ? { _key_array: key } : key;
19
+ };
20
+ class Lock {
21
+ constructor(_id, action, collection) {
22
+ this._id = _id;
23
+ this.action = action;
24
+ this.collection = collection;
25
+ this.locked = true;
26
+ if (this.locked) {
27
+ (() => __awaiter(this, void 0, void 0, function* () {
28
+ while (this.locked) {
29
+ yield new Promise((resolve) => setTimeout(resolve, 10000));
30
+ yield this.refresh().catch(() => {
31
+ console.error("Failed to refresh lock", action);
32
+ });
33
+ }
34
+ }))();
35
+ }
36
+ }
37
+ /**
38
+ * Instead of calling `this.free` directly you can use the `using` syntax
39
+ *
40
+ * @returns true if the lock was successfully released. False if the lock was not found
41
+ */
42
+ free() {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ if (!this.locked) {
45
+ return false;
46
+ }
47
+ this.locked = false;
48
+ const result = yield this.collection.deleteOne({ _id: this._id });
49
+ return result.deletedCount === 1;
50
+ });
51
+ }
52
+ /**
53
+ * Refreshes the lock's TTL
54
+ *
55
+ * Automatically called every 10 seconds if the lock is still active, no
56
+ * need to call this manually
57
+ *
58
+ * @returns true if the lock was successfully refreshed. False if the lock was not found
59
+ */
60
+ refresh() {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ if (!this.locked) {
63
+ return false;
64
+ }
65
+ const res = yield this.collection.updateOne({ _id: this._id }, { $set: { refreshedAt: new Date(), expiresAt: new Date(Date.now() + 60000) } });
66
+ this.locked = res.matchedCount === 1;
67
+ return this.locked;
68
+ });
69
+ }
70
+ [Symbol.dispose]() {
71
+ this.free();
72
+ }
73
+ [Symbol.asyncDispose]() {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ return this.free();
76
+ });
77
+ }
78
+ }
79
+ export class LockManager {
80
+ constructor(collection) {
81
+ this.MongoLocksError = MongoLocksError;
82
+ this.collection = collection;
83
+ collection.createIndex({ action: 1 }, { unique: true });
84
+ collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
85
+ }
86
+ /**
87
+ * Creates a DB lock based on the key provided
88
+ *
89
+ * @returns a function that when called will release the lock
90
+ */
91
+ lock(key) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ const lockId = makeKey(key);
94
+ const id = new ObjectId();
95
+ try {
96
+ yield this.collection.insertOne({
97
+ _id: id,
98
+ action: lockId,
99
+ createdAt: new Date(),
100
+ refreshedAt: new Date(),
101
+ expiresAt: new Date(Date.now() + 60000),
102
+ });
103
+ return new Lock(id, lockId, this.collection);
104
+ }
105
+ catch (err) {
106
+ if (err instanceof Error && "code" in err && err.code === 11000) {
107
+ return null;
108
+ }
109
+ throw err;
110
+ }
111
+ });
112
+ }
113
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "mongo-locks",
3
- "version": "3.0.2",
3
+ "type": "module",
4
+ "version": "3.1.1",
4
5
  "description": "Simple and bountiful locks to avoid doing the same operation multiple times",
5
- "main": "dist/index.js",
6
+ "main": "./dist/commonjs/index.js",
6
7
  "scripts": {
7
8
  "test": "echo \"Error: no test specified\" && exit 1",
8
- "prepublishOnly": "npm run clean && tsc",
9
- "clean": "rm -Rf dist"
9
+ "prepare": "tshy"
10
10
  },
11
11
  "repository": {
12
12
  "type": "git",
@@ -29,14 +29,35 @@
29
29
  "mongodb": ">=4"
30
30
  },
31
31
  "devDependencies": {
32
- "@types/node": "^20.12.7",
32
+ "@types/node": "^22.12.7",
33
33
  "mongodb": "^6.5.0",
34
+ "tshy": "^3.1.0",
34
35
  "typescript": "^5.4.5"
35
36
  },
36
37
  "files": [
37
38
  "dist",
38
- "index.d.ts",
39
- "index.ts",
39
+ "src",
40
40
  "tsconfig.json"
41
- ]
41
+ ],
42
+ "tshy": {
43
+ "exports": {
44
+ "./package.json": "./package.json",
45
+ ".": "./src/index.ts"
46
+ }
47
+ },
48
+ "exports": {
49
+ "./package.json": "./package.json",
50
+ ".": {
51
+ "import": {
52
+ "types": "./dist/esm/index.d.ts",
53
+ "default": "./dist/esm/index.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/commonjs/index.d.ts",
57
+ "default": "./dist/commonjs/index.js"
58
+ }
59
+ }
60
+ },
61
+ "types": "./dist/commonjs/index.d.ts",
62
+ "module": "./dist/esm/index.js"
42
63
  }
File without changes
File without changes