@naturalcycles/js-lib 14.81.0 → 14.84.0

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 (43) hide show
  1. package/dist/decorators/asyncMemo.decorator.d.ts +22 -0
  2. package/dist/decorators/asyncMemo.decorator.js +96 -0
  3. package/dist/decorators/memo.decorator.d.ts +8 -0
  4. package/dist/decorators/memo.decorator.js +11 -6
  5. package/dist/decorators/memo.util.d.ts +27 -8
  6. package/dist/decorators/memo.util.js +1 -1
  7. package/dist/error/error.model.d.ts +6 -0
  8. package/dist/index.d.ts +3 -3
  9. package/dist/index.js +1 -1
  10. package/dist/promise/AggregatedError.d.ts +1 -1
  11. package/dist/promise/AggregatedError.js +2 -7
  12. package/dist/promise/pFilter.d.ts +2 -3
  13. package/dist/promise/pFilter.js +4 -4
  14. package/dist/promise/pMap.d.ts +1 -1
  15. package/dist/promise/pMap.js +67 -19
  16. package/dist/promise/pRetry.d.ts +6 -2
  17. package/dist/promise/pRetry.js +6 -1
  18. package/dist/promise/pTimeout.d.ts +5 -1
  19. package/dist/promise/pTimeout.js +5 -1
  20. package/dist-esm/decorators/asyncMemo.decorator.js +104 -0
  21. package/dist-esm/decorators/memo.decorator.js +11 -5
  22. package/dist-esm/decorators/memo.util.js +1 -1
  23. package/dist-esm/index.js +1 -1
  24. package/dist-esm/promise/AggregatedError.js +2 -7
  25. package/dist-esm/promise/pFilter.js +4 -4
  26. package/dist-esm/promise/pMap.js +79 -19
  27. package/dist-esm/promise/pRetry.js +3 -1
  28. package/dist-esm/promise/pTimeout.js +2 -1
  29. package/package.json +1 -1
  30. package/src/decorators/asyncMemo.decorator.ts +151 -0
  31. package/src/decorators/memo.decorator.ts +16 -5
  32. package/src/decorators/memo.util.ts +36 -10
  33. package/src/error/error.model.ts +7 -0
  34. package/src/index.ts +3 -2
  35. package/src/promise/AggregatedError.ts +3 -8
  36. package/src/promise/pFilter.ts +5 -14
  37. package/src/promise/pMap.ts +72 -21
  38. package/src/promise/pRetry.ts +13 -3
  39. package/src/promise/pTimeout.ts +14 -2
  40. package/dist/promise/pBatch.d.ts +0 -7
  41. package/dist/promise/pBatch.js +0 -30
  42. package/dist-esm/promise/pBatch.js +0 -23
  43. package/src/promise/pBatch.ts +0 -31
@@ -0,0 +1,104 @@
1
+ import { __asyncValues } from "tslib";
2
+ import { _since } from '../time/time.util';
3
+ import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util';
4
+ import { CACHE_DROP } from './memo.decorator';
5
+ import { jsonMemoSerializer } from './memo.util';
6
+ /**
7
+ * Like @_Memo, but allowing async MemoCache implementation.
8
+ *
9
+ * Method CANNOT return `undefined`, as undefined will always be treated as cache MISS and retried.
10
+ * Return `null` instead (it'll be cached).
11
+ */
12
+ // eslint-disable-next-line @typescript-eslint/naming-convention
13
+ export const _AsyncMemo = (opt) => (target, key, descriptor) => {
14
+ if (typeof descriptor.value !== 'function') {
15
+ throw new TypeError('Memoization can be applied only to methods');
16
+ }
17
+ const originalFn = descriptor.value;
18
+ // Map from "instance" of the Class where @_AsyncMemo is applied to AsyncMemoCache instance.
19
+ const cache = new Map();
20
+ const { logHit = false, logMiss = false, noLogArgs = false, logger = console, cacheFactory, cacheKeyFn = jsonMemoSerializer, noCacheRejected = false, noCacheResolved = false, } = opt;
21
+ const keyStr = String(key);
22
+ const methodSignature = _getTargetMethodSignature(target, keyStr);
23
+ descriptor.value = async function (...args) {
24
+ var e_1, _a;
25
+ const ctx = this;
26
+ const cacheKey = cacheKeyFn(args);
27
+ if (!cache.has(ctx)) {
28
+ cache.set(ctx, cacheFactory());
29
+ // here, no need to check the cache. It's definitely a miss, because the cacheLayers is just created
30
+ // UPD: no! AsyncMemo supports "persistent caches" (e.g Database-backed cache)
31
+ }
32
+ if (args.length === 1 && args[0] === CACHE_DROP) {
33
+ // Special event - CACHE_DROP
34
+ // Function will return undefined
35
+ logger.log(`${methodSignature} @_AsyncMemo.dropCache()`);
36
+ try {
37
+ await Promise.all(cache.get(ctx).map(c => c.clear()));
38
+ }
39
+ catch (err) {
40
+ logger.error(err);
41
+ }
42
+ return;
43
+ }
44
+ let value;
45
+ try {
46
+ try {
47
+ for (var _b = __asyncValues(cache.get(ctx)), _c; _c = await _b.next(), !_c.done;) {
48
+ const cacheLayer = _c.value;
49
+ value = await cacheLayer.get(cacheKey);
50
+ if (value !== undefined) {
51
+ // it's a hit!
52
+ break;
53
+ }
54
+ }
55
+ }
56
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
57
+ finally {
58
+ try {
59
+ if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);
60
+ }
61
+ finally { if (e_1) throw e_1.error; }
62
+ }
63
+ }
64
+ catch (err) {
65
+ // log error, but don't throw, treat it as a "miss"
66
+ logger.error(err);
67
+ }
68
+ if (value !== undefined) {
69
+ // hit!
70
+ if (logHit) {
71
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_AsyncMemo hit`);
72
+ }
73
+ return value instanceof Error ? Promise.reject(value) : Promise.resolve(value);
74
+ }
75
+ // Here we know it's a MISS, let's execute the real method
76
+ const started = Date.now();
77
+ try {
78
+ value = await originalFn.apply(ctx, args);
79
+ if (!noCacheResolved) {
80
+ Promise.all(cache.get(ctx).map(cacheLayer => cacheLayer.set(cacheKey, value))).catch(err => {
81
+ // log and ignore the error
82
+ logger.error(err);
83
+ });
84
+ }
85
+ return value;
86
+ }
87
+ catch (err) {
88
+ if (!noCacheRejected) {
89
+ // We put it to cache as raw Error, not Promise.reject(err)
90
+ Promise.all(cache.get(ctx).map(cacheLayer => cacheLayer.set(cacheKey, err))).catch(err => {
91
+ // log and ignore the error
92
+ logger.error(err);
93
+ });
94
+ }
95
+ throw err;
96
+ }
97
+ finally {
98
+ if (logMiss) {
99
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_AsyncMemo miss (${_since(started)})`);
100
+ }
101
+ }
102
+ };
103
+ return descriptor;
104
+ };
@@ -6,6 +6,10 @@
6
6
  import { _since } from '../time/time.util';
7
7
  import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util';
8
8
  import { jsonMemoSerializer, MapMemoCache } from './memo.util';
9
+ /**
10
+ * Symbol to indicate that the Cache should be dropped.
11
+ */
12
+ export const CACHE_DROP = Symbol('CACHE_DROP');
9
13
  /**
10
14
  * Memoizes the method of the class, so it caches the output and returns the cached version if the "key"
11
15
  * of the cache is the same. Key, by defaul, is calculated as `JSON.stringify(...args)`.
@@ -35,7 +39,14 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
35
39
  const keyStr = String(key);
36
40
  const methodSignature = _getTargetMethodSignature(target, keyStr);
37
41
  descriptor.value = function (...args) {
42
+ var _a;
38
43
  const ctx = this;
44
+ if (args.length === 1 && args[0] === CACHE_DROP) {
45
+ // Special event - CACHE_DROP
46
+ // Function will return undefined
47
+ logger.log(`${methodSignature} @_Memo.CACHE_DROP`);
48
+ return (_a = cache.get(ctx)) === null || _a === void 0 ? void 0 : _a.clear();
49
+ }
39
50
  const cacheKey = cacheKeyFn(args);
40
51
  if (!cache.has(ctx)) {
41
52
  cache.set(ctx, cacheFactory());
@@ -88,10 +99,5 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
88
99
  return res;
89
100
  }
90
101
  };
91
- descriptor.value.dropCache = () => {
92
- logger.log(`${methodSignature} @_Memo.dropCache()`);
93
- cache.forEach(memoCache => memoCache.clear());
94
- cache.clear();
95
- };
96
102
  return descriptor;
97
103
  };
@@ -1,6 +1,6 @@
1
1
  import { _isPrimitive } from '../object/object.util';
2
2
  export const jsonMemoSerializer = args => {
3
- if (!args.length)
3
+ if (args.length === 0)
4
4
  return undefined;
5
5
  if (args.length === 1 && _isPrimitive(args[0]))
6
6
  return args[0];
package/dist-esm/index.js CHANGED
@@ -8,6 +8,7 @@ export * from './decorators/debounce.decorator';
8
8
  export * from './decorators/decorator.util';
9
9
  export * from './decorators/logMethod.decorator';
10
10
  export * from './decorators/memo.decorator';
11
+ export * from './decorators/asyncMemo.decorator';
11
12
  export * from './decorators/memoFn';
12
13
  export * from './decorators/retry.decorator';
13
14
  export * from './decorators/timeout.decorator';
@@ -31,7 +32,6 @@ export * from './object/object.util';
31
32
  export * from './object/sortObject';
32
33
  export * from './object/sortObjectDeep';
33
34
  import { AggregatedError } from './promise/AggregatedError';
34
- export * from './promise/pBatch';
35
35
  import { pDefer } from './promise/pDefer';
36
36
  export * from './promise/pDelay';
37
37
  export * from './promise/pFilter';
@@ -5,17 +5,12 @@
5
5
  */
6
6
  export class AggregatedError extends Error {
7
7
  constructor(errors, results = []) {
8
- const mappedErrors = errors.map(e => {
9
- if (typeof e === 'string')
10
- return new Error(e);
11
- return e;
12
- });
13
8
  const message = [
14
9
  `${errors.length} errors:`,
15
- ...mappedErrors.map((e, i) => `${i + 1}. ${e.message}`),
10
+ ...errors.map((e, i) => `${i + 1}. ${e.message}`),
16
11
  ].join('\n');
17
12
  super(message);
18
- this.errors = mappedErrors;
13
+ this.errors = errors;
19
14
  this.results = results;
20
15
  Object.defineProperty(this, 'name', {
21
16
  value: this.constructor.name,
@@ -1,5 +1,5 @@
1
- import { pMap } from './pMap';
2
- export async function pFilter(iterable, filterFn, opt) {
3
- const values = await pMap(iterable, async (item, index) => await Promise.all([filterFn(item, index), item]), opt);
4
- return values.filter(value => Boolean(value[0])).map(value => value[1]);
1
+ export async function pFilter(iterable, filterFn) {
2
+ const items = [...iterable];
3
+ const predicates = await Promise.all(items.map((item, i) => filterFn(item, i)));
4
+ return items.filter((item, i) => predicates[i]);
5
5
  }
@@ -6,6 +6,7 @@ Improvements:
6
6
  - Included Typescript typings (no need for @types/p-map)
7
7
  - Compatible with pProps (that had typings issues)
8
8
  */
9
+ import { __asyncValues } from "tslib";
9
10
  import { END, ErrorMode, SKIP } from '..';
10
11
  import { AggregatedError } from './AggregatedError';
11
12
  /**
@@ -35,28 +36,85 @@ import { AggregatedError } from './AggregatedError';
35
36
  * })();
36
37
  */
37
38
  export async function pMap(iterable, mapper, opt = {}) {
39
+ var e_1, _a;
40
+ const ret = [];
41
+ // const iterator = iterable[Symbol.iterator]()
42
+ const items = [...iterable];
43
+ const itemsLength = items.length;
44
+ if (itemsLength === 0)
45
+ return []; // short circuit
46
+ const { concurrency = itemsLength, errorMode = ErrorMode.THROW_IMMEDIATELY } = opt;
47
+ const errors = [];
48
+ let isSettled = false;
49
+ let resolvingCount = 0;
50
+ let currentIndex = 0;
51
+ // Special cases that are able to preserve async stack traces
52
+ if (concurrency === 1) {
53
+ try {
54
+ // Special case for concurrency == 1
55
+ for (var items_1 = __asyncValues(items), items_1_1; items_1_1 = await items_1.next(), !items_1_1.done;) {
56
+ const item = items_1_1.value;
57
+ try {
58
+ const r = await mapper(item, currentIndex++);
59
+ if (r === END)
60
+ break;
61
+ if (r !== SKIP)
62
+ ret.push(r);
63
+ }
64
+ catch (err) {
65
+ if (errorMode === ErrorMode.THROW_IMMEDIATELY)
66
+ throw err;
67
+ if (errorMode === ErrorMode.THROW_AGGREGATED) {
68
+ errors.push(err);
69
+ }
70
+ // otherwise, suppress completely
71
+ }
72
+ }
73
+ }
74
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
75
+ finally {
76
+ try {
77
+ if (items_1_1 && !items_1_1.done && (_a = items_1.return)) await _a.call(items_1);
78
+ }
79
+ finally { if (e_1) throw e_1.error; }
80
+ }
81
+ if (errors.length) {
82
+ throw new AggregatedError(errors, ret);
83
+ }
84
+ return ret;
85
+ }
86
+ else if (!opt.concurrency || items.length <= opt.concurrency) {
87
+ // Special case for concurrency == infinity or iterable.length < concurrency
88
+ if (errorMode === ErrorMode.THROW_IMMEDIATELY) {
89
+ return (await Promise.all(items.map((item, i) => mapper(item, i)))).filter(r => r !== SKIP && r !== END);
90
+ }
91
+ ;
92
+ (await Promise.allSettled(items.map((item, i) => mapper(item, i)))).forEach(r => {
93
+ if (r.status === 'fulfilled') {
94
+ if (r.value !== SKIP && r.value !== END)
95
+ ret.push(r.value);
96
+ }
97
+ else if (errorMode === ErrorMode.THROW_AGGREGATED) {
98
+ errors.push(r.reason);
99
+ }
100
+ });
101
+ if (errors.length) {
102
+ throw new AggregatedError(errors, ret);
103
+ }
104
+ return ret;
105
+ }
38
106
  return new Promise((resolve, reject) => {
39
- const { concurrency = Number.POSITIVE_INFINITY, errorMode = ErrorMode.THROW_IMMEDIATELY } = opt;
40
- const ret = [];
41
- const iterator = iterable[Symbol.iterator]();
42
- const errors = [];
43
- let isSettled = false;
44
- let isIterableDone = false;
45
- let resolvingCount = 0;
46
- let currentIndex = 0;
47
- const next = (skipped = false) => {
107
+ const next = () => {
48
108
  if (isSettled) {
49
109
  return;
50
110
  }
51
- const nextItem = iterator.next();
52
- const i = currentIndex;
53
- if (!skipped)
54
- currentIndex++;
55
- if (nextItem.done) {
56
- isIterableDone = true;
111
+ const nextItem = items[currentIndex];
112
+ const i = currentIndex++;
113
+ if (currentIndex > itemsLength) {
57
114
  if (resolvingCount === 0) {
115
+ isSettled = true;
58
116
  const r = ret.filter(r => r !== SKIP);
59
- if (errors.length && errorMode === ErrorMode.THROW_AGGREGATED) {
117
+ if (errors.length) {
60
118
  reject(new AggregatedError(errors, r));
61
119
  }
62
120
  else {
@@ -66,7 +124,7 @@ export async function pMap(iterable, mapper, opt = {}) {
66
124
  return;
67
125
  }
68
126
  resolvingCount++;
69
- Promise.resolve(nextItem.value)
127
+ Promise.resolve(nextItem)
70
128
  .then(async (element) => await mapper(element, i))
71
129
  .then(value => {
72
130
  if (value === END) {
@@ -82,7 +140,9 @@ export async function pMap(iterable, mapper, opt = {}) {
82
140
  reject(err);
83
141
  }
84
142
  else {
85
- errors.push(err);
143
+ if (errorMode === ErrorMode.THROW_AGGREGATED) {
144
+ errors.push(err);
145
+ }
86
146
  resolvingCount--;
87
147
  next();
88
148
  }
@@ -90,7 +150,7 @@ export async function pMap(iterable, mapper, opt = {}) {
90
150
  };
91
151
  for (let i = 0; i < concurrency; i++) {
92
152
  next();
93
- if (isIterableDone) {
153
+ if (isSettled) {
94
154
  break;
95
155
  }
96
156
  }
@@ -27,7 +27,7 @@ export async function pRetry(fn, opt = {}) {
27
27
  return await new Promise((resolve, reject) => {
28
28
  const rejectWithTimeout = () => {
29
29
  timedOut = true; // to prevent more tries
30
- const err = new TimeoutError(`"${fname}" timed out after ${timeout} ms`);
30
+ const err = new TimeoutError(`"${fname}" timed out after ${timeout} ms`, opt.errorData);
31
31
  if (fakeError) {
32
32
  // keep original stack
33
33
  err.stack = fakeError.stack.replace('Error: RetryError', 'TimeoutError');
@@ -71,6 +71,8 @@ export async function pRetry(fn, opt = {}) {
71
71
  fakeError.stack.replace('Error: RetryError', ''),
72
72
  });
73
73
  }
74
+ ;
75
+ err.data = Object.assign(Object.assign({}, err.data), opt.errorData);
74
76
  reject(err);
75
77
  }
76
78
  else {
@@ -32,11 +32,12 @@ export async function pTimeout(promise, opt) {
32
32
  catch (err) {
33
33
  if (fakeError)
34
34
  err.stack = fakeError.stack; // keep original stack
35
+ err.data = Object.assign(Object.assign({}, err.data), opt.errorData);
35
36
  reject(err);
36
37
  }
37
38
  return;
38
39
  }
39
- const err = new TimeoutError(`"${name || 'pTimeout function'}" timed out after ${timeout} ms`);
40
+ const err = new TimeoutError(`"${name || 'pTimeout function'}" timed out after ${timeout} ms`, opt.errorData);
40
41
  if (fakeError)
41
42
  err.stack = fakeError.stack; // keep original stack
42
43
  reject(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.81.0",
3
+ "version": "14.84.0",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -0,0 +1,151 @@
1
+ import { _since } from '../time/time.util'
2
+ import { Merge } from '../typeFest'
3
+ import { AnyObject } from '../types'
4
+ import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util'
5
+ import { CACHE_DROP, MemoOptions } from './memo.decorator'
6
+ import { AsyncMemoCache, jsonMemoSerializer } from './memo.util'
7
+
8
+ export type AsyncMemoOptions = Merge<
9
+ MemoOptions,
10
+ {
11
+ /**
12
+ * Provide a custom implementation of MemoCache.
13
+ * Function that creates an instance of `MemoCache`.
14
+ * e.g LRUMemoCache from `@naturalcycles/nodejs-lib`.
15
+ *
16
+ * It's an ARRAY of Caches, to allow multiple layers of Cache.
17
+ * It will check it one by one, starting from the first.
18
+ * HIT will be returned immediately, MISS will go one level deeper, or returned (if the end of the Cache stack is reached).
19
+ */
20
+ cacheFactory: () => AsyncMemoCache[]
21
+ }
22
+ >
23
+
24
+ /**
25
+ * Like @_Memo, but allowing async MemoCache implementation.
26
+ *
27
+ * Method CANNOT return `undefined`, as undefined will always be treated as cache MISS and retried.
28
+ * Return `null` instead (it'll be cached).
29
+ */
30
+ // eslint-disable-next-line @typescript-eslint/naming-convention
31
+ export const _AsyncMemo =
32
+ (opt: AsyncMemoOptions): MethodDecorator =>
33
+ (target, key, descriptor) => {
34
+ if (typeof descriptor.value !== 'function') {
35
+ throw new TypeError('Memoization can be applied only to methods')
36
+ }
37
+
38
+ const originalFn = descriptor.value
39
+
40
+ // Map from "instance" of the Class where @_AsyncMemo is applied to AsyncMemoCache instance.
41
+ const cache = new Map<AnyObject, AsyncMemoCache[]>()
42
+
43
+ const {
44
+ logHit = false,
45
+ logMiss = false,
46
+ noLogArgs = false,
47
+ logger = console,
48
+ cacheFactory,
49
+ cacheKeyFn = jsonMemoSerializer,
50
+ noCacheRejected = false,
51
+ noCacheResolved = false,
52
+ } = opt
53
+
54
+ const keyStr = String(key)
55
+ const methodSignature = _getTargetMethodSignature(target, keyStr)
56
+
57
+ descriptor.value = async function (this: typeof target, ...args: any[]): Promise<any> {
58
+ const ctx = this
59
+
60
+ const cacheKey = cacheKeyFn(args)
61
+
62
+ if (!cache.has(ctx)) {
63
+ cache.set(ctx, cacheFactory())
64
+ // here, no need to check the cache. It's definitely a miss, because the cacheLayers is just created
65
+ // UPD: no! AsyncMemo supports "persistent caches" (e.g Database-backed cache)
66
+ }
67
+
68
+ if (args.length === 1 && args[0] === CACHE_DROP) {
69
+ // Special event - CACHE_DROP
70
+ // Function will return undefined
71
+ logger.log(`${methodSignature} @_AsyncMemo.dropCache()`)
72
+ try {
73
+ await Promise.all(cache.get(ctx)!.map(c => c.clear()))
74
+ } catch (err) {
75
+ logger.error(err)
76
+ }
77
+
78
+ return
79
+ }
80
+
81
+ let value: any
82
+
83
+ try {
84
+ for await (const cacheLayer of cache.get(ctx)!) {
85
+ value = await cacheLayer.get(cacheKey)
86
+ if (value !== undefined) {
87
+ // it's a hit!
88
+ break
89
+ }
90
+ }
91
+ } catch (err) {
92
+ // log error, but don't throw, treat it as a "miss"
93
+ logger.error(err)
94
+ }
95
+
96
+ if (value !== undefined) {
97
+ // hit!
98
+ if (logHit) {
99
+ logger.log(
100
+ `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
101
+ args,
102
+ noLogArgs,
103
+ )}) @_AsyncMemo hit`,
104
+ )
105
+ }
106
+
107
+ return value instanceof Error ? Promise.reject(value) : Promise.resolve(value)
108
+ }
109
+
110
+ // Here we know it's a MISS, let's execute the real method
111
+ const started = Date.now()
112
+
113
+ try {
114
+ value = await originalFn.apply(ctx, args)
115
+
116
+ if (!noCacheResolved) {
117
+ Promise.all(cache.get(ctx)!.map(cacheLayer => cacheLayer.set(cacheKey, value))).catch(
118
+ err => {
119
+ // log and ignore the error
120
+ logger.error(err)
121
+ },
122
+ )
123
+ }
124
+
125
+ return value
126
+ } catch (err) {
127
+ if (!noCacheRejected) {
128
+ // We put it to cache as raw Error, not Promise.reject(err)
129
+ Promise.all(cache.get(ctx)!.map(cacheLayer => cacheLayer.set(cacheKey, err))).catch(
130
+ err => {
131
+ // log and ignore the error
132
+ logger.error(err)
133
+ },
134
+ )
135
+ }
136
+
137
+ throw err
138
+ } finally {
139
+ if (logMiss) {
140
+ logger.log(
141
+ `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
142
+ args,
143
+ noLogArgs,
144
+ )}) @_AsyncMemo miss (${_since(started)})`,
145
+ )
146
+ }
147
+ }
148
+ } as any
149
+
150
+ return descriptor
151
+ }
@@ -10,6 +10,11 @@ import { AnyObject } from '../types'
10
10
  import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util'
11
11
  import { jsonMemoSerializer, MapMemoCache, MemoCache } from './memo.util'
12
12
 
13
+ /**
14
+ * Symbol to indicate that the Cache should be dropped.
15
+ */
16
+ export const CACHE_DROP = Symbol('CACHE_DROP')
17
+
13
18
  export interface MemoOptions {
14
19
  /**
15
20
  * Default to false
@@ -45,12 +50,16 @@ export interface MemoOptions {
45
50
  /**
46
51
  * Don't cache resolved promises.
47
52
  * Setting this to `true` will make the decorator to await the result.
53
+ *
54
+ * Default false.
48
55
  */
49
56
  noCacheResolved?: boolean
50
57
 
51
58
  /**
52
59
  * Don't cache rejected promises.
53
60
  * Setting this to `true` will make the decorator to await the result.
61
+ *
62
+ * Default false.
54
63
  */
55
64
  noCacheRejected?: boolean
56
65
  }
@@ -102,6 +111,13 @@ export const _Memo =
102
111
  descriptor.value = function (this: typeof target, ...args: any[]): any {
103
112
  const ctx = this
104
113
 
114
+ if (args.length === 1 && args[0] === CACHE_DROP) {
115
+ // Special event - CACHE_DROP
116
+ // Function will return undefined
117
+ logger.log(`${methodSignature} @_Memo.CACHE_DROP`)
118
+ return cache.get(ctx)?.clear()
119
+ }
120
+
105
121
  const cacheKey = cacheKeyFn(args)
106
122
 
107
123
  if (!cache.has(ctx)) {
@@ -179,11 +195,6 @@ export const _Memo =
179
195
  return res
180
196
  }
181
197
  } as any
182
- ;(descriptor.value as any).dropCache = () => {
183
- logger.log(`${methodSignature} @_Memo.dropCache()`)
184
- cache.forEach(memoCache => memoCache.clear())
185
- cache.clear()
186
- }
187
198
 
188
199
  return descriptor
189
200
  }
@@ -1,20 +1,44 @@
1
1
  import { _isPrimitive } from '../object/object.util'
2
+ import { Promisable } from '../typeFest'
2
3
 
3
4
  export type MemoSerializer = (args: any[]) => any
4
5
 
5
6
  export const jsonMemoSerializer: MemoSerializer = args => {
6
- if (!args.length) return undefined
7
+ if (args.length === 0) return undefined
7
8
  if (args.length === 1 && _isPrimitive(args[0])) return args[0]
8
9
  return JSON.stringify(args)
9
10
  }
10
11
 
11
- export interface MemoCache {
12
- has(k: any): boolean
13
- get(k: any): any
14
- set(k: any, v: any): void
12
+ export interface MemoCache<KEY = any, VALUE = any> {
13
+ has(k: KEY): boolean
14
+ get(k: KEY): VALUE | undefined
15
+ set(k: KEY, v: VALUE): void
16
+
17
+ /**
18
+ * Clear is only called when `.dropCache()` is called.
19
+ * Otherwise the Cache is "persistent" (never cleared).
20
+ */
15
21
  clear(): void
16
22
  }
17
23
 
24
+ export interface AsyncMemoCache<KEY = any, VALUE = any> {
25
+ // `has` method is removed, because it is assumed that it has a cost and it's best to avoid doing both `has` and then `get`
26
+ // has(k: any): Promise<boolean>
27
+ /**
28
+ * `undefined` value returned indicates the ABSENCE of value in the Cache.
29
+ * This also means that you CANNOT store `undefined` value in the Cache, as it'll be treated as a MISS.
30
+ * You CAN store `null` value instead, it will be treated as a HIT.
31
+ */
32
+ get(k: KEY): Promisable<VALUE | undefined>
33
+ set(k: KEY, v: VALUE): Promisable<void>
34
+
35
+ /**
36
+ * Clear is only called when `.dropCache()` is called.
37
+ * Otherwise the Cache is "persistent" (never cleared).
38
+ */
39
+ clear(): Promisable<void>
40
+ }
41
+
18
42
  // SingleValueMemoCache and ObjectMemoCache are example-only, not used in production code
19
43
  /*
20
44
  export class SingleValueMemoCache implements MemoCache {
@@ -61,18 +85,20 @@ export class ObjectMemoCache implements MemoCache {
61
85
  }
62
86
  */
63
87
 
64
- export class MapMemoCache implements MemoCache {
65
- private m = new Map<any, any>()
88
+ export class MapMemoCache<KEY = any, VALUE = any>
89
+ implements MemoCache<KEY, VALUE>, AsyncMemoCache<KEY, VALUE>
90
+ {
91
+ private m = new Map<KEY, VALUE>()
66
92
 
67
- has(k: any): boolean {
93
+ has(k: KEY): boolean {
68
94
  return this.m.has(k)
69
95
  }
70
96
 
71
- get(k: any): any {
97
+ get(k: KEY): VALUE | undefined {
72
98
  return this.m.get(k)
73
99
  }
74
100
 
75
- set(k: any, v: any): void {
101
+ set(k: KEY, v: VALUE): void {
76
102
  this.m.set(k, v)
77
103
  }
78
104
 
@@ -31,6 +31,13 @@ export interface ErrorData {
31
31
  */
32
32
  originalMessage?: string
33
33
 
34
+ /**
35
+ * Can be used by error-reporting tools (e.g Sentry).
36
+ * If fingerprint is defined - it'll be used INSTEAD of default fingerprint of a tool.
37
+ * Can be used to force-group errors that are NOT needed to be split by endpoint or calling function.
38
+ */
39
+ fingerprint?: string[]
40
+
34
41
  /**
35
42
  * Open-ended.
36
43
  */