@storyous/mongodb 1.7.0 → 1.7.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.
Files changed (48) hide show
  1. package/README.md +134 -134
  2. package/lib/appData/index.d.ts +12 -12
  3. package/lib/appData/index.js +39 -39
  4. package/lib/appData/index.ts +48 -48
  5. package/lib/concurrentTask.d.ts +9 -9
  6. package/lib/concurrentTask.js +19 -19
  7. package/lib/concurrentTask.ts +30 -30
  8. package/lib/fixtures.d.ts +5 -5
  9. package/lib/fixtures.js +27 -27
  10. package/lib/fixtures.ts +36 -36
  11. package/lib/getCollection.d.ts +3 -3
  12. package/lib/getCollection.js +8 -8
  13. package/lib/getCollection.ts +5 -5
  14. package/lib/getMongoConfig.d.ts +6 -6
  15. package/lib/getMongoConfig.js +85 -85
  16. package/lib/getMongoConfig.ts +78 -78
  17. package/lib/getMongoLocker.d.ts +10 -10
  18. package/lib/getMongoLocker.js +52 -52
  19. package/lib/getMongoLocker.ts +71 -71
  20. package/lib/global-bundle.pem +2876 -2876
  21. package/lib/index.d.ts +14 -13
  22. package/lib/index.js +34 -32
  23. package/lib/index.ts +32 -30
  24. package/lib/migrations/Migration.d.ts +6 -6
  25. package/lib/migrations/Migration.js +21 -21
  26. package/lib/migrations/Migration.ts +29 -29
  27. package/lib/migrations/MigrationsStore.d.ts +13 -13
  28. package/lib/migrations/MigrationsStore.js +64 -64
  29. package/lib/migrations/MigrationsStore.ts +81 -81
  30. package/lib/migrations/runMigrations.d.ts +12 -12
  31. package/lib/migrations/runMigrations.js +49 -49
  32. package/lib/migrations/runMigrations.ts +57 -57
  33. package/lib/migrations/template.d.ts +3 -3
  34. package/lib/migrations/template.js +10 -10
  35. package/lib/migrations/template.ts +7 -7
  36. package/lib/mongoClient.d.ts +8 -8
  37. package/lib/mongoClient.js +17 -17
  38. package/lib/mongoClient.ts +25 -25
  39. package/lib/mongoErrorCodes.d.ts +6 -6
  40. package/lib/mongoErrorCodes.js +10 -10
  41. package/lib/mongoErrorCodes.ts +10 -10
  42. package/lib/mongoLocker.d.ts +3 -3
  43. package/lib/mongoLocker.js +16 -16
  44. package/lib/mongoLocker.ts +15 -15
  45. package/lib/withTransaction.d.ts +3 -3
  46. package/lib/withTransaction.js +20 -20
  47. package/lib/withTransaction.ts +24 -24
  48. package/package.json +2 -2
package/README.md CHANGED
@@ -1,134 +1,134 @@
1
- # `mongodb`
2
-
3
- ## Usage of MongoClient
4
-
5
- ``` typescript
6
- import { mongoClient } from '@storyous/mongodb';
7
-
8
- // Initialize and connect MongoDB
9
- mongoClient.init('mongodb://127.0.0.1:27017');
10
- await mongoClient.getClient().connect();
11
-
12
- // Useage of MongoClient
13
- const user = mongoClient.getClient().db('test').collection('users').find();
14
-
15
- // Close current connection
16
- await mongoClient.getClient().close();
17
- ```
18
-
19
- ## Usage of getMongoConfig
20
-
21
- ``` typescript
22
- import { getMongoConfig, mongoClient } from '@storyous/mongodb';
23
-
24
- // Set following env variables:
25
- // DOCUMENTDB_ENGINE="mongodb" (or "documentdb")
26
- // DOCUMENTDB_ENDPOINT="127.0.0.1"
27
- // DOCUMENTDB_USER="user"
28
- // DOCUMENTDB_PASSWORD="password"
29
- //
30
- // Optional env variables (and default values)
31
- // DOCUMENTDB_DATABASE=""
32
- // DOCUMENTDB_PORT="27017"
33
- // DOCUMENTDB_PROTOCOL="mongodb"
34
- // DOCUMENTDB_QUERY="?retryWrites=false"
35
-
36
- // Get config
37
- const config = {
38
- database: {
39
- ...getMongoConfig(),
40
- }
41
- };
42
-
43
- // Initialize and connect MongoDB
44
- mongoClient.init(config.database.mongodbUrl, config.database.mongoOptions);
45
- ```
46
-
47
- You can also use custom prefix for environment variables (e.g. MY_DB_ENGINE, MY_DB_ENDPOINT, ...):
48
- ```typescript
49
- getMongoConfig('MY_DB');
50
- ```
51
-
52
- ## Usage of MongoLocker
53
-
54
- ``` typescript
55
- import { getMongoLocker, mongoLocker } from '@storyous/mongodb';
56
-
57
- // default mongoLocker instance
58
- const locker = mongoLocker();
59
- const callback = () => {}
60
- const result1 = await locker('someKey', callback);
61
-
62
- // custom mongoLocker instance
63
- const locker = getMongoLocker('nameOfMyCollecrion');
64
- const callback = () => {}
65
- const result1 = await locker('someKey', callback);
66
- ```
67
-
68
- ## Usage of Fixtures
69
-
70
- ``` typescript
71
- import { fixtures, mongoClient } from '@storyous/mongodb';
72
-
73
- const collection = mongoClient.getClient().db().collection('currency');
74
- const currencyFixtures = [
75
- { _id: new ObjectId(), name: 'CZK' },
76
- { _id: new ObjectId(), name: 'EUR' },
77
- ];
78
- await fixtures.ensureInCollection(currencyFixtures, collection);
79
- ```
80
-
81
- ## Usage of WithTransaction
82
-
83
- ``` typescript
84
- import { mongoClient, withTransaction } from '@storyous/mongodb';
85
-
86
- const collection = mongoClient.getClient().db().collection('currency');
87
- const returnValue = await withTransaction(async (session) => {
88
- await testCollection.insertOne({}, { session });
89
-
90
- return true;
91
- });
92
- ```
93
-
94
- ## Usage of AppData
95
-
96
- ``` typescript
97
- import { appData } from '@storyous/mongodb';
98
-
99
- const testDocument = { _id: new ObjectId() };
100
- await appData.ensureDocumentExists(testDocument);
101
- await appData.updateDocument(testDocument._id, { $set: { foo: 'bar' } });
102
- await appData.getDocument(testDocument._id);
103
- ```
104
-
105
- ## Usage of Migrations
106
-
107
- ### Generation of new migration
108
- Add this target into your package.json:
109
-
110
- `"migrate:create": "migrate create --migrations-dir ./migrations --template-file ./node_modules/@storyous/mongodb/lib/migrations/template.ts"`
111
-
112
- Run target by npm:
113
-
114
- `npm run migrate:create nameOfMyMigration`
115
-
116
- ### Run migration
117
- ``` typescript
118
- import { runMigrations } from '@storyous/mongodb';
119
-
120
- await runMigrations(createLogger(), `${__dirname}/migrations`, {
121
- safeMigration: config.mongoSafeMigration
122
- });
123
- ```
124
-
125
- note: The "safeMigration" needs to be false on testing and localhost environment.
126
- And it should be true on TEST and PROD.
127
-
128
- safeMigration: true does not run migration if it does not find any migration data in database
129
- or it is trying to run all migrations from beginning.
130
-
131
- On first deploy to TEST/PROD you need to setup it to "false". Then it should be changed to "true"
132
-
133
- Reason: Once it happened on production that the migrations history were erased for unknown reason
134
- and the migration started again - which caused a lot of issues. safeMigration: true should prevent it.
1
+ # `mongodb`
2
+
3
+ ## Usage of MongoClient
4
+
5
+ ``` typescript
6
+ import { mongoClient } from '@storyous/mongodb';
7
+
8
+ // Initialize and connect MongoDB
9
+ mongoClient.init('mongodb://127.0.0.1:27017');
10
+ await mongoClient.getClient().connect();
11
+
12
+ // Useage of MongoClient
13
+ const user = mongoClient.getClient().db('test').collection('users').find();
14
+
15
+ // Close current connection
16
+ await mongoClient.getClient().close();
17
+ ```
18
+
19
+ ## Usage of getMongoConfig
20
+
21
+ ``` typescript
22
+ import { getMongoConfig, mongoClient } from '@storyous/mongodb';
23
+
24
+ // Set following env variables:
25
+ // DOCUMENTDB_ENGINE="mongodb" (or "documentdb")
26
+ // DOCUMENTDB_ENDPOINT="127.0.0.1"
27
+ // DOCUMENTDB_USER="user"
28
+ // DOCUMENTDB_PASSWORD="password"
29
+ //
30
+ // Optional env variables (and default values)
31
+ // DOCUMENTDB_DATABASE=""
32
+ // DOCUMENTDB_PORT="27017"
33
+ // DOCUMENTDB_PROTOCOL="mongodb"
34
+ // DOCUMENTDB_QUERY="?retryWrites=false"
35
+
36
+ // Get config
37
+ const config = {
38
+ database: {
39
+ ...getMongoConfig(),
40
+ }
41
+ };
42
+
43
+ // Initialize and connect MongoDB
44
+ mongoClient.init(config.database.mongodbUrl, config.database.mongoOptions);
45
+ ```
46
+
47
+ You can also use custom prefix for environment variables (e.g. MY_DB_ENGINE, MY_DB_ENDPOINT, ...):
48
+ ```typescript
49
+ getMongoConfig('MY_DB');
50
+ ```
51
+
52
+ ## Usage of MongoLocker
53
+
54
+ ``` typescript
55
+ import { getMongoLocker, mongoLocker } from '@storyous/mongodb';
56
+
57
+ // default mongoLocker instance
58
+ const locker = mongoLocker();
59
+ const callback = () => {}
60
+ const result1 = await locker('someKey', callback);
61
+
62
+ // custom mongoLocker instance
63
+ const locker = getMongoLocker('nameOfMyCollecrion');
64
+ const callback = () => {}
65
+ const result1 = await locker('someKey', callback);
66
+ ```
67
+
68
+ ## Usage of Fixtures
69
+
70
+ ``` typescript
71
+ import { fixtures, mongoClient } from '@storyous/mongodb';
72
+
73
+ const collection = mongoClient.getClient().db().collection('currency');
74
+ const currencyFixtures = [
75
+ { _id: new ObjectId(), name: 'CZK' },
76
+ { _id: new ObjectId(), name: 'EUR' },
77
+ ];
78
+ await fixtures.ensureInCollection(currencyFixtures, collection);
79
+ ```
80
+
81
+ ## Usage of WithTransaction
82
+
83
+ ``` typescript
84
+ import { mongoClient, withTransaction } from '@storyous/mongodb';
85
+
86
+ const collection = mongoClient.getClient().db().collection('currency');
87
+ const returnValue = await withTransaction(async (session) => {
88
+ await testCollection.insertOne({}, { session });
89
+
90
+ return true;
91
+ });
92
+ ```
93
+
94
+ ## Usage of AppData
95
+
96
+ ``` typescript
97
+ import { appData } from '@storyous/mongodb';
98
+
99
+ const testDocument = { _id: new ObjectId() };
100
+ await appData.ensureDocumentExists(testDocument);
101
+ await appData.updateDocument(testDocument._id, { $set: { foo: 'bar' } });
102
+ await appData.getDocument(testDocument._id);
103
+ ```
104
+
105
+ ## Usage of Migrations
106
+
107
+ ### Generation of new migration
108
+ Add this target into your package.json:
109
+
110
+ `"migrate:create": "migrate create --migrations-dir ./migrations --template-file ./node_modules/@storyous/mongodb/lib/migrations/template.ts"`
111
+
112
+ Run target by npm:
113
+
114
+ `npm run migrate:create nameOfMyMigration`
115
+
116
+ ### Run migration
117
+ ``` typescript
118
+ import { runMigrations } from '@storyous/mongodb';
119
+
120
+ await runMigrations(createLogger(), `${__dirname}/migrations`, {
121
+ safeMigration: config.mongoSafeMigration
122
+ });
123
+ ```
124
+
125
+ note: The "safeMigration" needs to be false on testing and localhost environment.
126
+ And it should be true on TEST and PROD.
127
+
128
+ safeMigration: true does not run migration if it does not find any migration data in database
129
+ or it is trying to run all migrations from beginning.
130
+
131
+ On first deploy to TEST/PROD you need to setup it to "false". Then it should be changed to "true"
132
+
133
+ Reason: Once it happened on production that the migrations history were erased for unknown reason
134
+ and the migration started again - which caused a lot of issues. safeMigration: true should prevent it.
@@ -1,12 +1,12 @@
1
- import { Collection, InsertOneResult, WithId } from 'mongodb';
2
- import { Key } from '../mongoClient';
3
- declare const appData: {
4
- readonly _collection: Collection<any>;
5
- _failReads: number;
6
- ensureDocumentExists(document: {
7
- _id: Key;
8
- }): Promise<Document | InsertOneResult | null>;
9
- updateDocument(_id: Key, update: Object, upsert?: boolean): Promise<WithId<any | null>>;
10
- getDocument(_id: Key): Promise<WithId<any | null>>;
11
- };
12
- export default appData;
1
+ import { Collection, InsertOneResult, WithId } from 'mongodb';
2
+ import { Key } from '../mongoClient';
3
+ declare const appData: {
4
+ readonly _collection: Collection<any>;
5
+ _failReads: number;
6
+ ensureDocumentExists(document: {
7
+ _id: Key;
8
+ }): Promise<Document | InsertOneResult | null>;
9
+ updateDocument(_id: Key, update: Object, upsert?: boolean): Promise<WithId<any | null>>;
10
+ getDocument(_id: Key): Promise<WithId<any | null>>;
11
+ };
12
+ export default appData;
@@ -1,40 +1,40 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const getCollection_1 = __importDefault(require("../getCollection"));
7
- const mongoDuplicateKeyErrorCodes = [11000, 11001];
8
- const appData = {
9
- get _collection() {
10
- return (0, getCollection_1.default)('appData');
11
- },
12
- _failReads: 0,
13
- ensureDocumentExists(document) {
14
- return this._collection
15
- .insertOne(document)
16
- .catch((err) => (new Promise((resolve, reject) => {
17
- if (!mongoDuplicateKeyErrorCodes.includes(err.code)) {
18
- reject(err);
19
- return;
20
- }
21
- resolve(null);
22
- })));
23
- },
24
- updateDocument(_id, update, upsert = false) {
25
- const query = { _id };
26
- const options = {
27
- returnOriginal: false,
28
- upsert,
29
- };
30
- return this._collection
31
- .findOneAndUpdate(query, update, options)
32
- .then((result) => result.value);
33
- },
34
- getDocument(_id) {
35
- const query = { _id };
36
- return this._collection.findOne(query);
37
- },
38
- };
39
- exports.default = appData;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const getCollection_1 = __importDefault(require("../getCollection"));
7
+ const mongoDuplicateKeyErrorCodes = [11000, 11001];
8
+ const appData = {
9
+ get _collection() {
10
+ return (0, getCollection_1.default)('appData');
11
+ },
12
+ _failReads: 0,
13
+ ensureDocumentExists(document) {
14
+ return this._collection
15
+ .insertOne(document)
16
+ .catch((err) => (new Promise((resolve, reject) => {
17
+ if (!mongoDuplicateKeyErrorCodes.includes(err.code)) {
18
+ reject(err);
19
+ return;
20
+ }
21
+ resolve(null);
22
+ })));
23
+ },
24
+ updateDocument(_id, update, upsert = false) {
25
+ const query = { _id };
26
+ const options = {
27
+ returnOriginal: false,
28
+ upsert,
29
+ };
30
+ return this._collection
31
+ .findOneAndUpdate(query, update, options)
32
+ .then((result) => result.value);
33
+ },
34
+ getDocument(_id) {
35
+ const query = { _id };
36
+ return this._collection.findOne(query);
37
+ },
38
+ };
39
+ exports.default = appData;
40
40
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUNBLHFFQUE2QztBQUc3QyxNQUFNLDJCQUEyQixHQUFHLENBQUMsS0FBSyxFQUFFLEtBQUssQ0FBQyxDQUFDO0FBRW5ELE1BQU0sT0FBTyxHQUFHO0lBRVosSUFBSSxXQUFXO1FBQ1gsT0FBTyxJQUFBLHVCQUFhLEVBQUMsU0FBUyxDQUFDLENBQUM7SUFDcEMsQ0FBQztJQUVELFVBQVUsRUFBRSxDQUFDO0lBRWIsb0JBQW9CLENBQUUsUUFBc0I7UUFDeEMsT0FBTyxJQUFJLENBQUMsV0FBVzthQUNsQixTQUFTLENBQUMsUUFBZSxDQUFDO2FBQzFCLEtBQUssQ0FBQyxDQUFDLEdBQVEsRUFBRSxFQUFFLENBQUMsQ0FDakIsSUFBSSxPQUFPLENBQUMsQ0FBQyxPQUFPLEVBQUUsTUFBTSxFQUFFLEVBQUU7WUFDNUIsSUFBSSxDQUFDLDJCQUEyQixDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLEVBQUU7Z0JBQ2pELE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztnQkFFWixPQUFPO2FBQ1Y7WUFDRCxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDbEIsQ0FBQyxDQUFDLENBQ0wsQ0FBQyxDQUFDO0lBQ1gsQ0FBQztJQUVELGNBQWMsQ0FBRSxHQUFRLEVBQUUsTUFBYyxFQUFFLFNBQWtCLEtBQUs7UUFDN0QsTUFBTSxLQUFLLEdBQUcsRUFBRSxHQUFHLEVBQUUsQ0FBQztRQUN0QixNQUFNLE9BQU8sR0FBRztZQUNaLGNBQWMsRUFBRSxLQUFLO1lBQ3JCLE1BQU07U0FDVCxDQUFDO1FBQ0YsT0FBTyxJQUFJLENBQUMsV0FBVzthQUNsQixnQkFBZ0IsQ0FBQyxLQUFLLEVBQUUsTUFBTSxFQUFFLE9BQU8sQ0FBQzthQUN4QyxJQUFJLENBQUMsQ0FBQyxNQUFNLEVBQUUsRUFBRSxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQztJQUN4QyxDQUFDO0lBRUQsV0FBVyxDQUFFLEdBQVE7UUFDakIsTUFBTSxLQUFLLEdBQUcsRUFBRSxHQUFHLEVBQUUsQ0FBQztRQUN0QixPQUFPLElBQUksQ0FBQyxXQUFXLENBQUMsT0FBTyxDQUFDLEtBQUssQ0FBQyxDQUFDO0lBQzNDLENBQUM7Q0FFSixDQUFDO0FBRUYsa0JBQWUsT0FBTyxDQUFDIn0=
@@ -1,48 +1,48 @@
1
- import { Collection, InsertOneResult, WithId } from 'mongodb';
2
- import getCollection from '../getCollection';
3
- import { Key } from '../mongoClient';
4
-
5
- const mongoDuplicateKeyErrorCodes = [11000, 11001];
6
-
7
- const appData = {
8
-
9
- get _collection (): Collection<any> {
10
- return getCollection('appData');
11
- },
12
-
13
- _failReads: 0,
14
-
15
- ensureDocumentExists (document: { _id: Key }): Promise<Document | InsertOneResult | null> {
16
- return this._collection
17
- .insertOne(document as any)
18
- .catch((err: any) => (
19
- new Promise((resolve, reject) => {
20
- if (!mongoDuplicateKeyErrorCodes.includes(err.code)) {
21
- reject(err);
22
-
23
- return;
24
- }
25
- resolve(null);
26
- })
27
- ));
28
- },
29
-
30
- updateDocument (_id: Key, update: Object, upsert: boolean = false): Promise<WithId<any| null>> {
31
- const query = { _id };
32
- const options = {
33
- returnOriginal: false,
34
- upsert,
35
- };
36
- return this._collection
37
- .findOneAndUpdate(query, update, options)
38
- .then((result) => result.value);
39
- },
40
-
41
- getDocument (_id: Key): Promise<WithId<any| null>> {
42
- const query = { _id };
43
- return this._collection.findOne(query);
44
- },
45
-
46
- };
47
-
48
- export default appData;
1
+ import { Collection, InsertOneResult, WithId } from 'mongodb';
2
+ import getCollection from '../getCollection';
3
+ import { Key } from '../mongoClient';
4
+
5
+ const mongoDuplicateKeyErrorCodes = [11000, 11001];
6
+
7
+ const appData = {
8
+
9
+ get _collection (): Collection<any> {
10
+ return getCollection('appData');
11
+ },
12
+
13
+ _failReads: 0,
14
+
15
+ ensureDocumentExists (document: { _id: Key }): Promise<Document | InsertOneResult | null> {
16
+ return this._collection
17
+ .insertOne(document as any)
18
+ .catch((err: any) => (
19
+ new Promise((resolve, reject) => {
20
+ if (!mongoDuplicateKeyErrorCodes.includes(err.code)) {
21
+ reject(err);
22
+
23
+ return;
24
+ }
25
+ resolve(null);
26
+ })
27
+ ));
28
+ },
29
+
30
+ updateDocument (_id: Key, update: Object, upsert: boolean = false): Promise<WithId<any| null>> {
31
+ const query = { _id };
32
+ const options = {
33
+ returnOriginal: false,
34
+ upsert,
35
+ };
36
+ return this._collection
37
+ .findOneAndUpdate(query, update, options)
38
+ .then((result) => result.value);
39
+ },
40
+
41
+ getDocument (_id: Key): Promise<WithId<any| null>> {
42
+ const query = { _id };
43
+ return this._collection.findOne(query);
44
+ },
45
+
46
+ };
47
+
48
+ export default appData;
@@ -1,9 +1,9 @@
1
- /**
2
- * noLaterThan = In what time by now should be the latest attempt executed
3
- * startAttemptsDelay = Starting attempts delay
4
- */
5
- declare const concurrentTask: <T>(task: () => Promise<T>, { noLaterThan, startAttemptsDelay }?: {
6
- noLaterThan?: number | undefined;
7
- startAttemptsDelay?: number | undefined;
8
- }) => Promise<any>;
9
- export default concurrentTask;
1
+ /**
2
+ * noLaterThan = In what time by now should be the latest attempt executed
3
+ * startAttemptsDelay = Starting attempts delay
4
+ */
5
+ declare const concurrentTask: <T>(task: () => Promise<T>, { noLaterThan, startAttemptsDelay }?: {
6
+ noLaterThan?: number | undefined;
7
+ startAttemptsDelay?: number | undefined;
8
+ }) => Promise<any>;
9
+ export default concurrentTask;
@@ -1,20 +1,20 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const errors_1 = require("@storyous/errors");
4
- const attemptRecursive = async (task, startAttemptsDelay, latestTime, callNumber) => (task().catch(async (err) => {
5
- if (errors_1.AppError.isConcurrentRequestError(err)) {
6
- const nextCallDelay = startAttemptsDelay * (callNumber ** 2);
7
- if ((Date.now() + nextCallDelay) < latestTime) {
8
- await new Promise((resolve) => { setTimeout(resolve, nextCallDelay); });
9
- return attemptRecursive(task, startAttemptsDelay, latestTime, ++callNumber);
10
- }
11
- }
12
- throw err;
13
- }));
14
- /**
15
- * noLaterThan = In what time by now should be the latest attempt executed
16
- * startAttemptsDelay = Starting attempts delay
17
- */
18
- const concurrentTask = async (task, { noLaterThan = 2000, startAttemptsDelay = 50 } = {}) => (attemptRecursive(task, startAttemptsDelay, Date.now() + noLaterThan, 1));
19
- exports.default = concurrentTask;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const errors_1 = require("@storyous/errors");
4
+ const attemptRecursive = async (task, startAttemptsDelay, latestTime, callNumber) => (task().catch(async (err) => {
5
+ if (errors_1.AppError.isConcurrentRequestError(err)) {
6
+ const nextCallDelay = startAttemptsDelay * (callNumber ** 2);
7
+ if ((Date.now() + nextCallDelay) < latestTime) {
8
+ await new Promise((resolve) => { setTimeout(resolve, nextCallDelay); });
9
+ return attemptRecursive(task, startAttemptsDelay, latestTime, ++callNumber);
10
+ }
11
+ }
12
+ throw err;
13
+ }));
14
+ /**
15
+ * noLaterThan = In what time by now should be the latest attempt executed
16
+ * startAttemptsDelay = Starting attempts delay
17
+ */
18
+ const concurrentTask = async (task, { noLaterThan = 2000, startAttemptsDelay = 50 } = {}) => (attemptRecursive(task, startAttemptsDelay, Date.now() + noLaterThan, 1));
19
+ exports.default = concurrentTask;
20
20
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uY3VycmVudFRhc2suanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJjb25jdXJyZW50VGFzay50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLDZDQUE0QztBQUU1QyxNQUFNLGdCQUFnQixHQUFHLEtBQUssRUFDMUIsSUFBc0IsRUFDdEIsa0JBQTBCLEVBQzFCLFVBQWtCLEVBQ2xCLFVBQWtCLEVBQ04sRUFBRSxDQUFDLENBQ2YsSUFBSSxFQUFFLENBQUMsS0FBSyxDQUFDLEtBQUssRUFBRSxHQUFVLEVBQUUsRUFBRTtJQUM5QixJQUFJLGlCQUFRLENBQUMsd0JBQXdCLENBQUMsR0FBRyxDQUFDLEVBQUU7UUFDeEMsTUFBTSxhQUFhLEdBQUcsa0JBQWtCLEdBQUcsQ0FBQyxVQUFVLElBQUksQ0FBQyxDQUFDLENBQUM7UUFDN0QsSUFBSSxDQUFDLElBQUksQ0FBQyxHQUFHLEVBQUUsR0FBRyxhQUFhLENBQUMsR0FBRyxVQUFVLEVBQUU7WUFDM0MsTUFBTSxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFFLEdBQUcsVUFBVSxDQUFDLE9BQU8sRUFBRSxhQUFhLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQ3hFLE9BQU8sZ0JBQWdCLENBQUMsSUFBSSxFQUFFLGtCQUFrQixFQUFFLFVBQVUsRUFBRSxFQUFFLFVBQVUsQ0FBQyxDQUFDO1NBQy9FO0tBQ0o7SUFFRCxNQUFNLEdBQUcsQ0FBQztBQUNkLENBQUMsQ0FBQyxDQUNMLENBQUM7QUFFRjs7O0dBR0c7QUFDSCxNQUFNLGNBQWMsR0FBRyxLQUFLLEVBQU0sSUFBc0IsRUFBRSxFQUFFLFdBQVcsR0FBRyxJQUFJLEVBQUUsa0JBQWtCLEdBQUcsRUFBRSxFQUFFLEdBQUcsRUFBRSxFQUFFLEVBQUUsQ0FBQyxDQUMvRyxnQkFBZ0IsQ0FBQyxJQUFJLEVBQUUsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLFdBQVcsRUFBRSxDQUFDLENBQUMsQ0FDMUUsQ0FBQztBQUVGLGtCQUFlLGNBQWMsQ0FBQyJ9
@@ -1,30 +1,30 @@
1
- import { AppError } from '@storyous/errors';
2
-
3
- const attemptRecursive = async <T> (
4
- task: () => Promise<T>,
5
- startAttemptsDelay: number,
6
- latestTime: number,
7
- callNumber: number,
8
- ): Promise<any> => (
9
- task().catch(async (err: Error) => {
10
- if (AppError.isConcurrentRequestError(err)) {
11
- const nextCallDelay = startAttemptsDelay * (callNumber ** 2);
12
- if ((Date.now() + nextCallDelay) < latestTime) {
13
- await new Promise((resolve) => { setTimeout(resolve, nextCallDelay); });
14
- return attemptRecursive(task, startAttemptsDelay, latestTime, ++callNumber);
15
- }
16
- }
17
-
18
- throw err;
19
- })
20
- );
21
-
22
- /**
23
- * noLaterThan = In what time by now should be the latest attempt executed
24
- * startAttemptsDelay = Starting attempts delay
25
- */
26
- const concurrentTask = async <T> (task: () => Promise<T>, { noLaterThan = 2000, startAttemptsDelay = 50 } = {}) => (
27
- attemptRecursive(task, startAttemptsDelay, Date.now() + noLaterThan, 1)
28
- );
29
-
30
- export default concurrentTask;
1
+ import { AppError } from '@storyous/errors';
2
+
3
+ const attemptRecursive = async <T> (
4
+ task: () => Promise<T>,
5
+ startAttemptsDelay: number,
6
+ latestTime: number,
7
+ callNumber: number,
8
+ ): Promise<any> => (
9
+ task().catch(async (err: Error) => {
10
+ if (AppError.isConcurrentRequestError(err)) {
11
+ const nextCallDelay = startAttemptsDelay * (callNumber ** 2);
12
+ if ((Date.now() + nextCallDelay) < latestTime) {
13
+ await new Promise((resolve) => { setTimeout(resolve, nextCallDelay); });
14
+ return attemptRecursive(task, startAttemptsDelay, latestTime, ++callNumber);
15
+ }
16
+ }
17
+
18
+ throw err;
19
+ })
20
+ );
21
+
22
+ /**
23
+ * noLaterThan = In what time by now should be the latest attempt executed
24
+ * startAttemptsDelay = Starting attempts delay
25
+ */
26
+ const concurrentTask = async <T> (task: () => Promise<T>, { noLaterThan = 2000, startAttemptsDelay = 50 } = {}) => (
27
+ attemptRecursive(task, startAttemptsDelay, Date.now() + noLaterThan, 1)
28
+ );
29
+
30
+ export default concurrentTask;
package/lib/fixtures.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Collection, Document } from 'mongodb';
2
- declare const fixtures: {
3
- ensureInCollection(_fixtures: Document[], collection: Collection): Promise<any>;
4
- };
5
- export default fixtures;
1
+ import { Collection, Document } from 'mongodb';
2
+ declare const fixtures: {
3
+ ensureInCollection(_fixtures: Document[], collection: Collection): Promise<any>;
4
+ };
5
+ export default fixtures;