@naturalcycles/js-lib 14.84.0 → 14.85.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 (43) hide show
  1. package/dist/decorators/asyncMemo.decorator.d.ts +35 -9
  2. package/dist/decorators/asyncMemo.decorator.js +39 -34
  3. package/dist/decorators/decorator.util.d.ts +1 -1
  4. package/dist/decorators/decorator.util.js +2 -2
  5. package/dist/decorators/logMethod.decorator.d.ts +6 -4
  6. package/dist/decorators/logMethod.decorator.js +3 -3
  7. package/dist/decorators/memo.decorator.d.ts +29 -29
  8. package/dist/decorators/memo.decorator.js +42 -53
  9. package/dist/decorators/memo.util.d.ts +6 -6
  10. package/dist/decorators/memoFn.d.ts +5 -0
  11. package/dist/decorators/memoFn.js +32 -37
  12. package/dist/decorators/memoFnAsync.d.ts +10 -0
  13. package/dist/decorators/memoFnAsync.js +69 -0
  14. package/dist/decorators/memoSimple.decorator.d.ts +1 -1
  15. package/dist/decorators/memoSimple.decorator.js +3 -3
  16. package/dist/error/assert.d.ts +4 -4
  17. package/dist/error/error.model.d.ts +1 -0
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +1 -0
  20. package/dist/promise/pRetry.d.ts +2 -2
  21. package/dist/promise/pTimeout.d.ts +3 -2
  22. package/dist-esm/decorators/asyncMemo.decorator.js +40 -47
  23. package/dist-esm/decorators/decorator.util.js +2 -2
  24. package/dist-esm/decorators/logMethod.decorator.js +3 -3
  25. package/dist-esm/decorators/memo.decorator.js +41 -53
  26. package/dist-esm/decorators/memoFn.js +32 -37
  27. package/dist-esm/decorators/memoFnAsync.js +65 -0
  28. package/dist-esm/decorators/memoSimple.decorator.js +3 -3
  29. package/dist-esm/index.js +1 -0
  30. package/package.json +1 -1
  31. package/src/decorators/asyncMemo.decorator.ts +88 -61
  32. package/src/decorators/decorator.util.ts +2 -2
  33. package/src/decorators/logMethod.decorator.ts +16 -7
  34. package/src/decorators/memo.decorator.ts +66 -102
  35. package/src/decorators/memo.util.ts +7 -7
  36. package/src/decorators/memoFn.ts +33 -51
  37. package/src/decorators/memoFnAsync.ts +91 -0
  38. package/src/decorators/memoSimple.decorator.ts +4 -4
  39. package/src/error/assert.ts +4 -4
  40. package/src/error/error.model.ts +2 -0
  41. package/src/index.ts +1 -0
  42. package/src/promise/pRetry.ts +2 -2
  43. package/src/promise/pTimeout.ts +3 -2
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._memoFnAsync = void 0;
4
+ const time_util_1 = require("../time/time.util");
5
+ const decorator_util_1 = require("./decorator.util");
6
+ const memo_util_1 = require("./memo.util");
7
+ /**
8
+ * Only supports Sync functions.
9
+ * To support Async functions - use _memoFnAsync
10
+ */
11
+ function _memoFnAsync(fn, opt = {}) {
12
+ const { logHit = false, logMiss = false, logArgs = true, logger = console, cacheRejections = true, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, } = opt;
13
+ const cache = cacheFactory();
14
+ const fnName = fn.name;
15
+ const memoizedFn = async function (...args) {
16
+ const ctx = this;
17
+ const cacheKey = cacheKeyFn(args);
18
+ let value;
19
+ try {
20
+ value = await cache.get(cacheKey);
21
+ }
22
+ catch (err) {
23
+ logger.error(err);
24
+ }
25
+ if (value !== undefined) {
26
+ if (logHit) {
27
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, logArgs)}) memoFnAsync hit`);
28
+ }
29
+ if (value instanceof Error) {
30
+ throw value;
31
+ }
32
+ return value;
33
+ }
34
+ const started = Date.now();
35
+ try {
36
+ value = await fn.apply(ctx, args);
37
+ void (async () => {
38
+ try {
39
+ await cache.set(cacheKey, value);
40
+ }
41
+ catch (err) {
42
+ logger.error(err);
43
+ }
44
+ })();
45
+ return value;
46
+ }
47
+ catch (err) {
48
+ if (cacheRejections) {
49
+ void (async () => {
50
+ try {
51
+ await cache.set(cacheKey, err);
52
+ }
53
+ catch (err) {
54
+ logger.error(err);
55
+ }
56
+ })();
57
+ }
58
+ throw err;
59
+ }
60
+ finally {
61
+ if (logMiss) {
62
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, logArgs)}) memoFnAsync miss (${(0, time_util_1._since)(started)})`);
63
+ }
64
+ }
65
+ };
66
+ Object.assign(memoizedFn, { cache });
67
+ return memoizedFn;
68
+ }
69
+ exports._memoFnAsync = _memoFnAsync;
@@ -2,7 +2,7 @@ import { CommonLogger } from '../log/commonLogger';
2
2
  export interface MemoOpts {
3
3
  logHit?: boolean;
4
4
  logMiss?: boolean;
5
- noLogArgs?: boolean;
5
+ logArgs?: boolean;
6
6
  logger?: CommonLogger;
7
7
  }
8
8
  /**
@@ -37,7 +37,7 @@ const memoSimple = (opt = {}) => (target, key, descriptor) => {
37
37
  }
38
38
  */
39
39
  const cache = new memo_util_1.MapMemoCache();
40
- const { logHit, logMiss, noLogArgs, logger = console } = opt;
40
+ const { logHit, logMiss, logArgs = true, logger = console } = opt;
41
41
  const keyStr = String(key);
42
42
  const methodSignature = (0, decorator_util_1._getTargetMethodSignature)(target, keyStr);
43
43
  descriptor.value = function (...args) {
@@ -45,14 +45,14 @@ const memoSimple = (opt = {}) => (target, key, descriptor) => {
45
45
  const cacheKey = (0, memo_util_1.jsonMemoSerializer)(args);
46
46
  if (cache.has(cacheKey)) {
47
47
  if (logHit) {
48
- logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo hit`);
48
+ logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, logArgs)}) @memo hit`);
49
49
  }
50
50
  return cache.get(cacheKey);
51
51
  }
52
52
  const d = Date.now();
53
53
  const res = originalFn.apply(ctx, args);
54
54
  if (logMiss) {
55
- logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss (${Date.now() - d} ms)`);
55
+ logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, logArgs)}) @memo miss (${Date.now() - d} ms)`);
56
56
  }
57
57
  cache.set(cacheKey, res);
58
58
  return res;
@@ -1,4 +1,4 @@
1
- import { ErrorData, HttpErrorData } from '..';
1
+ import { ErrorData } from '..';
2
2
  import { AppError } from './app.error';
3
3
  /**
4
4
  * Evaluates the `condition` (casts it to Boolean).
@@ -16,21 +16,21 @@ import { AppError } from './app.error';
16
16
  * 3. Sets `userFriendly` flag to true, cause it's always better to have at least SOME clue, rather than fully generic "Oops" error.
17
17
  */
18
18
  export declare function _assert(condition: any, // will be evaluated as Boolean
19
- message?: string, errorData?: Partial<HttpErrorData>): asserts condition;
19
+ message?: string, errorData?: ErrorData): asserts condition;
20
20
  /**
21
21
  * Like _assert(), but prints more helpful error message.
22
22
  * API is similar to Node's assert.equals().
23
23
  *
24
24
  * Does SHALLOW, but strict equality (===), use _assertDeepEquals() for deep equality.
25
25
  */
26
- export declare function _assertEquals<T>(actual: any, expected: T, message?: string, errorData?: Partial<HttpErrorData>): asserts actual is T;
26
+ export declare function _assertEquals<T>(actual: any, expected: T, message?: string, errorData?: ErrorData): asserts actual is T;
27
27
  /**
28
28
  * Like _assert(), but prints more helpful error message.
29
29
  * API is similar to Node's assert.deepEquals().
30
30
  *
31
31
  * Does DEEP equality via _deepEquals()
32
32
  */
33
- export declare function _assertDeepEquals<T>(actual: any, expected: T, message?: string, errorData?: Partial<HttpErrorData>): asserts actual is T;
33
+ export declare function _assertDeepEquals<T>(actual: any, expected: T, message?: string, errorData?: ErrorData): asserts actual is T;
34
34
  export declare function _assertIsError<ERR extends Error = Error>(err: any, message?: string): asserts err is ERR;
35
35
  export declare function _assertIsString(v: any, message?: string): asserts v is string;
36
36
  export declare function _assertIsNumber(v: any, message?: string): asserts v is number;
@@ -32,6 +32,7 @@ export interface ErrorData {
32
32
  * Can be used to force-group errors that are NOT needed to be split by endpoint or calling function.
33
33
  */
34
34
  fingerprint?: string[];
35
+ httpStatusCode?: number;
35
36
  /**
36
37
  * Open-ended.
37
38
  */
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export * from './decorators/memo.decorator';
11
11
  export * from './decorators/asyncMemo.decorator';
12
12
  import { MemoCache, AsyncMemoCache } from './decorators/memo.util';
13
13
  export * from './decorators/memoFn';
14
+ export * from './decorators/memoFnAsync';
14
15
  export * from './decorators/retry.decorator';
15
16
  export * from './decorators/timeout.decorator';
16
17
  export * from './error/app.error';
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "_createPromiseDecorator", { enumerable: true, ge
15
15
  (0, tslib_1.__exportStar)(require("./decorators/memo.decorator"), exports);
16
16
  (0, tslib_1.__exportStar)(require("./decorators/asyncMemo.decorator"), exports);
17
17
  (0, tslib_1.__exportStar)(require("./decorators/memoFn"), exports);
18
+ (0, tslib_1.__exportStar)(require("./decorators/memoFnAsync"), exports);
18
19
  (0, tslib_1.__exportStar)(require("./decorators/retry.decorator"), exports);
19
20
  (0, tslib_1.__exportStar)(require("./decorators/timeout.decorator"), exports);
20
21
  (0, tslib_1.__exportStar)(require("./error/app.error"), exports);
@@ -1,4 +1,4 @@
1
- import { AnyFunction, AnyObject, CommonLogger } from '..';
1
+ import { AnyFunction, CommonLogger, ErrorData } from '..';
2
2
  export interface PRetryOptions {
3
3
  /**
4
4
  * If set - will be included in the error message.
@@ -79,7 +79,7 @@ export interface PRetryOptions {
79
79
  /**
80
80
  * Will be merged with `err.data` object.
81
81
  */
82
- errorData?: AnyObject;
82
+ errorData?: ErrorData;
83
83
  }
84
84
  /**
85
85
  * Returns a Function (!), enhanced with retry capabilities.
@@ -1,5 +1,6 @@
1
1
  import { AppError } from '../error/app.error';
2
- import { AnyFunction, AnyObject } from '../types';
2
+ import { ErrorData } from '../error/error.model';
3
+ import { AnyFunction } from '../types';
3
4
  export declare class TimeoutError extends AppError {
4
5
  }
5
6
  export interface PTimeoutOptions {
@@ -28,7 +29,7 @@ export interface PTimeoutOptions {
28
29
  /**
29
30
  * Will be merged with `err.data` object.
30
31
  */
31
- errorData?: AnyObject;
32
+ errorData?: ErrorData;
32
33
  }
33
34
  /**
34
35
  * Decorates a Function with a timeout.
@@ -1,8 +1,6 @@
1
- import { __asyncValues } from "tslib";
2
1
  import { _since } from '../time/time.util';
3
2
  import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util';
4
- import { CACHE_DROP } from './memo.decorator';
5
- import { jsonMemoSerializer } from './memo.util';
3
+ import { jsonMemoSerializer, MapMemoCache } from './memo.util';
6
4
  /**
7
5
  * Like @_Memo, but allowing async MemoCache implementation.
8
6
  *
@@ -10,18 +8,17 @@ import { jsonMemoSerializer } from './memo.util';
10
8
  * Return `null` instead (it'll be cached).
11
9
  */
12
10
  // eslint-disable-next-line @typescript-eslint/naming-convention
13
- export const _AsyncMemo = (opt) => (target, key, descriptor) => {
11
+ export const _AsyncMemo = (opt = {}) => (target, key, descriptor) => {
14
12
  if (typeof descriptor.value !== 'function') {
15
13
  throw new TypeError('Memoization can be applied only to methods');
16
14
  }
17
15
  const originalFn = descriptor.value;
18
16
  // Map from "instance" of the Class where @_AsyncMemo is applied to AsyncMemoCache instance.
19
17
  const cache = new Map();
20
- const { logHit = false, logMiss = false, noLogArgs = false, logger = console, cacheFactory, cacheKeyFn = jsonMemoSerializer, noCacheRejected = false, noCacheResolved = false, } = opt;
18
+ const { logHit = false, logMiss = false, logArgs = true, logger = console, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, cacheRejections = true, } = opt;
21
19
  const keyStr = String(key);
22
20
  const methodSignature = _getTargetMethodSignature(target, keyStr);
23
21
  descriptor.value = async function (...args) {
24
- var e_1, _a;
25
22
  const ctx = this;
26
23
  const cacheKey = cacheKeyFn(args);
27
24
  if (!cache.has(ctx)) {
@@ -29,37 +26,9 @@ export const _AsyncMemo = (opt) => (target, key, descriptor) => {
29
26
  // here, no need to check the cache. It's definitely a miss, because the cacheLayers is just created
30
27
  // UPD: no! AsyncMemo supports "persistent caches" (e.g Database-backed cache)
31
28
  }
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
29
  let value;
45
30
  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
- }
31
+ value = await cache.get(ctx).get(cacheKey);
63
32
  }
64
33
  catch (err) {
65
34
  // log error, but don't throw, treat it as a "miss"
@@ -68,37 +37,61 @@ export const _AsyncMemo = (opt) => (target, key, descriptor) => {
68
37
  if (value !== undefined) {
69
38
  // hit!
70
39
  if (logHit) {
71
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_AsyncMemo hit`);
40
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, logArgs)}) @_AsyncMemo hit`);
41
+ }
42
+ if (value instanceof Error) {
43
+ throw value;
72
44
  }
73
- return value instanceof Error ? Promise.reject(value) : Promise.resolve(value);
45
+ return value;
74
46
  }
75
47
  // Here we know it's a MISS, let's execute the real method
76
48
  const started = Date.now();
77
49
  try {
78
50
  value = await originalFn.apply(ctx, args);
79
- if (!noCacheResolved) {
80
- Promise.all(cache.get(ctx).map(cacheLayer => cacheLayer.set(cacheKey, value))).catch(err => {
51
+ // Save the value in the Cache, without awaiting it
52
+ // This is to support both sync and async functions
53
+ void (async () => {
54
+ try {
55
+ await cache.get(ctx).set(cacheKey, value);
56
+ }
57
+ catch (err) {
81
58
  // log and ignore the error
82
59
  logger.error(err);
83
- });
84
- }
60
+ }
61
+ })();
85
62
  return value;
86
63
  }
87
64
  catch (err) {
88
- if (!noCacheRejected) {
65
+ if (cacheRejections) {
89
66
  // 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
- });
67
+ // This is to support both sync and async functions
68
+ void (async () => {
69
+ try {
70
+ await cache.get(ctx).set(cacheKey, err);
71
+ }
72
+ catch (err) {
73
+ // log and ignore the error
74
+ logger.error(err);
75
+ }
76
+ })();
94
77
  }
95
78
  throw err;
96
79
  }
97
80
  finally {
98
81
  if (logMiss) {
99
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_AsyncMemo miss (${_since(started)})`);
82
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, logArgs)}) @_AsyncMemo miss (${_since(started)})`);
100
83
  }
101
84
  }
102
85
  };
86
+ descriptor.value.dropCache = async () => {
87
+ logger.log(`${methodSignature} @_AsyncMemo.dropCache()`);
88
+ try {
89
+ await Promise.all([...cache.values()].map(c => c.clear()));
90
+ cache.clear();
91
+ }
92
+ catch (err) {
93
+ logger.error(err);
94
+ }
95
+ };
103
96
  return descriptor;
104
97
  };
@@ -19,8 +19,8 @@ export function _getTargetMethodSignature(target, keyStr) {
19
19
  * returns:
20
20
  * a, b, c
21
21
  */
22
- export function _getArgsSignature(args = [], noLogArgs = false) {
23
- if (noLogArgs)
22
+ export function _getArgsSignature(args = [], logArgs = true) {
23
+ if (!logArgs)
24
24
  return '';
25
25
  return args
26
26
  .map(arg => {
@@ -20,13 +20,13 @@ export function _LogMethod(opt = {}) {
20
20
  _assert(typeof descriptor.value === 'function', '@_LogMethod can be applied only to methods');
21
21
  const originalFn = descriptor.value;
22
22
  const keyStr = String(key);
23
- const { avg, noLogArgs, logStart, logResult, noLogResultLength, logger = console } = opt;
23
+ const { avg, logArgs = true, logStart, logResult, logResultLength = true, logger = console, } = opt;
24
24
  let { logResultFn } = opt;
25
25
  if (!logResultFn) {
26
26
  if (logResult) {
27
27
  logResultFn = r => ['result:', _stringifyAny(r)];
28
28
  }
29
- else if (!noLogResultLength) {
29
+ else if (logResultLength) {
30
30
  logResultFn = r => (Array.isArray(r) ? [`result: ${r.length} items`] : []);
31
31
  }
32
32
  }
@@ -38,7 +38,7 @@ export function _LogMethod(opt = {}) {
38
38
  // e.g `NameOfYourClass.methodName`
39
39
  // or `NameOfYourClass(instanceId).methodName`
40
40
  const methodSignature = _getMethodSignature(ctx, keyStr);
41
- const argsStr = _getArgsSignature(args, noLogArgs);
41
+ const argsStr = _getArgsSignature(args, logArgs);
42
42
  const callSignature = `${methodSignature}(${argsStr}) #${++count}`;
43
43
  if (logStart)
44
44
  logger.log(`>> ${callSignature}`);
@@ -1,15 +1,6 @@
1
- // Based on:
2
- // https://github.com/mgechev/memo-decorator/blob/master/index.ts
3
- // http://decodize.com/blog/2012/08/27/javascript-memoization-caching-results-for-better-performance/
4
- // http://inlehmansterms.net/2015/03/01/javascript-memoization/
5
- // https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
6
1
  import { _since } from '../time/time.util';
7
2
  import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util';
8
3
  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');
13
4
  /**
14
5
  * Memoizes the method of the class, so it caches the output and returns the cached version if the "key"
15
6
  * of the cache is the same. Key, by defaul, is calculated as `JSON.stringify(...args)`.
@@ -19,6 +10,15 @@ export const CACHE_DROP = Symbol('CACHE_DROP');
19
10
  * If you don't want it that way - you can use a static method, then there will be only one "instance".
20
11
  *
21
12
  * Supports dropping it's cache by calling .dropCache() method of decorated function (useful in unit testing).
13
+ *
14
+ * Doesn't support Async functions, use @_AsyncMemo instead!
15
+ * (or, it will simply return the [unresolved] Promise further, without awaiting it)
16
+ *
17
+ * Based on:
18
+ * https://github.com/mgechev/memo-decorator/blob/master/index.ts
19
+ * http://decodize.com/blog/2012/08/27/javascript-memoization-caching-results-for-better-performance/
20
+ * http://inlehmansterms.net/2015/03/01/javascript-memoization/
21
+ * https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
22
22
  */
23
23
  // eslint-disable-next-line @typescript-eslint/naming-convention
24
24
  export const _Memo = (opt = {}) => (target, key, descriptor) => {
@@ -34,70 +34,58 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
34
34
  // UPD: tests show that normal Map also doesn't leak (to be tested further)
35
35
  // Normal Map is needed to allow .dropCache()
36
36
  const cache = new Map();
37
- const { logHit = false, logMiss = false, noLogArgs = false, logger = console, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, noCacheRejected = false, noCacheResolved = false, } = opt;
38
- const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
37
+ const { logHit = false, logMiss = false, logArgs = true, logger = console, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, cacheErrors = true, } = opt;
39
38
  const keyStr = String(key);
40
39
  const methodSignature = _getTargetMethodSignature(target, keyStr);
41
40
  descriptor.value = function (...args) {
42
- var _a;
43
41
  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
- }
50
42
  const cacheKey = cacheKeyFn(args);
43
+ let value;
51
44
  if (!cache.has(ctx)) {
52
45
  cache.set(ctx, cacheFactory());
53
46
  }
54
47
  else if (cache.get(ctx).has(cacheKey)) {
55
48
  if (logHit) {
56
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo hit`);
57
- }
58
- const res = cache.get(ctx).get(cacheKey);
59
- if (awaitPromise) {
60
- return res instanceof Error ? Promise.reject(res) : Promise.resolve(res);
49
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, logArgs)}) @_Memo hit`);
61
50
  }
62
- else {
63
- return res;
51
+ value = cache.get(ctx).get(cacheKey);
52
+ if (value instanceof Error) {
53
+ throw value;
64
54
  }
55
+ return value;
65
56
  }
66
57
  const started = Date.now();
67
- const res = originalFn.apply(ctx, args);
68
- if (awaitPromise) {
69
- return res
70
- .then(res => {
71
- // console.log('RESOLVED', res)
72
- if (logMiss) {
73
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss resolved (${_since(started)})`);
74
- }
75
- if (!noCacheResolved) {
76
- cache.get(ctx).set(cacheKey, res);
77
- }
78
- return res;
79
- })
80
- .catch(err => {
81
- // console.log('REJECTED', err)
82
- if (logMiss) {
83
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss rejected (${_since(started)})`);
58
+ try {
59
+ value = originalFn.apply(ctx, args);
60
+ try {
61
+ cache.get(ctx).set(cacheKey, value);
62
+ }
63
+ catch (err) {
64
+ logger.error(err);
65
+ }
66
+ return value;
67
+ }
68
+ catch (err) {
69
+ if (cacheErrors) {
70
+ try {
71
+ cache.get(ctx).set(cacheKey, err);
84
72
  }
85
- if (!noCacheRejected) {
86
- // We put it to cache as raw Error, not Promise.reject(err)
87
- // So, we'll need to check if it's instanceof Error to reject it or resolve
88
- // Wrap as Error if it's not Error
89
- cache.get(ctx).set(cacheKey, err instanceof Error ? err : new Error(err));
73
+ catch (err) {
74
+ logger.error(err);
90
75
  }
91
- throw err;
92
- });
76
+ }
77
+ throw err;
93
78
  }
94
- else {
79
+ finally {
95
80
  if (logMiss) {
96
- logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss (${_since(started)})`);
81
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, logArgs)}) @_Memo miss (${_since(started)})`);
97
82
  }
98
- cache.get(ctx).set(cacheKey, res);
99
- return res;
100
83
  }
101
84
  };
85
+ descriptor.value.dropCache = () => {
86
+ logger.log(`${methodSignature} @_Memo.dropCache()`);
87
+ cache.forEach(memoCache => memoCache.clear());
88
+ cache.clear();
89
+ };
102
90
  return descriptor;
103
91
  };
@@ -1,60 +1,55 @@
1
1
  import { _since } from '../time/time.util';
2
2
  import { _getArgsSignature } from './decorator.util';
3
3
  import { jsonMemoSerializer, MapMemoCache } from './memo.util';
4
+ /**
5
+ * Only supports Sync functions.
6
+ * To support Async functions - use _memoFnAsync.
7
+ * Technically, you can use it with Async functions, but it'll return the Promise without awaiting it.
8
+ */
4
9
  export function _memoFn(fn, opt = {}) {
5
- const { logHit = false, logMiss = false, noLogArgs = false, logger = console, noCacheRejected = false, noCacheResolved = false, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
10
+ const { logHit = false, logMiss = false, logArgs = true, logger = console, cacheErrors = true, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
6
11
  const cache = cacheFactory();
7
- const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
8
12
  const fnName = fn.name;
9
13
  const memoizedFn = function (...args) {
10
14
  const ctx = this;
11
15
  const cacheKey = cacheKeyFn(args);
16
+ let value;
12
17
  if (cache.has(cacheKey)) {
13
18
  if (logHit) {
14
- logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn hit`);
19
+ logger.log(`${fnName}(${_getArgsSignature(args, logArgs)}) memoFn hit`);
15
20
  }
16
- const res = cache.get(cacheKey);
17
- if (awaitPromise) {
18
- return res instanceof Error ? Promise.reject(res) : Promise.resolve(res);
19
- }
20
- else {
21
- return res;
21
+ value = cache.get(cacheKey);
22
+ if (value instanceof Error) {
23
+ throw value;
22
24
  }
25
+ return value;
23
26
  }
24
27
  const started = Date.now();
25
- const res = fn.apply(ctx, args);
26
- if (awaitPromise) {
27
- return res
28
- .then(res => {
29
- // console.log('RESOLVED', res)
30
- if (logMiss) {
31
- logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss resolved (${_since(started)})`);
32
- }
33
- if (!noCacheResolved) {
34
- cache.set(cacheKey, res);
35
- }
36
- return res;
37
- })
38
- .catch(err => {
39
- // console.log('REJECTED', err)
40
- if (logMiss) {
41
- logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss rejected (${_since(started)})`);
28
+ try {
29
+ value = fn.apply(ctx, args);
30
+ try {
31
+ cache.set(cacheKey, value);
32
+ }
33
+ catch (err) {
34
+ logger.error(err);
35
+ }
36
+ return value;
37
+ }
38
+ catch (err) {
39
+ if (cacheErrors) {
40
+ try {
41
+ cache.set(cacheKey, err);
42
42
  }
43
- if (!noCacheRejected) {
44
- // We put it to cache as raw Error, not Promise.reject(err)
45
- // So, we'll need to check if it's instanceof Error to reject it or resolve
46
- // Wrap as Error if it's not Error
47
- cache.set(cacheKey, err instanceof Error ? err : new Error(err));
43
+ catch (err) {
44
+ logger.error(err);
48
45
  }
49
- throw err;
50
- });
46
+ }
47
+ throw err;
51
48
  }
52
- else {
49
+ finally {
53
50
  if (logMiss) {
54
- logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss (${_since(started)})`);
51
+ logger.log(`${fnName}(${_getArgsSignature(args, logArgs)}) memoFn miss (${_since(started)})`);
55
52
  }
56
- cache.set(cacheKey, res);
57
- return res;
58
53
  }
59
54
  };
60
55
  Object.assign(memoizedFn, { cache });