@naturalcycles/js-lib 14.80.0 → 14.83.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 (49) 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 +32 -8
  6. package/dist/decorators/memo.util.js +17 -2
  7. package/dist/decorators/retry.decorator.js +1 -1
  8. package/dist/error/error.model.d.ts +6 -0
  9. package/dist/index.d.ts +5 -5
  10. package/dist/index.js +3 -2
  11. package/dist/json-schema/jsonSchemaBuilder.d.ts +2 -2
  12. package/dist/json-schema/jsonSchemaBuilder.js +4 -4
  13. package/dist/json-schema/jsonSchemas.d.ts +2 -2
  14. package/dist/promise/AggregatedError.d.ts +1 -1
  15. package/dist/promise/AggregatedError.js +2 -7
  16. package/dist/promise/pFilter.d.ts +2 -3
  17. package/dist/promise/pFilter.js +4 -4
  18. package/dist/promise/pMap.d.ts +1 -1
  19. package/dist/promise/pMap.js +67 -19
  20. package/dist/promise/pRetry.d.ts +17 -2
  21. package/dist/promise/pRetry.js +72 -40
  22. package/dist/types.d.ts +5 -5
  23. package/dist-esm/decorators/asyncMemo.decorator.js +104 -0
  24. package/dist-esm/decorators/memo.decorator.js +11 -5
  25. package/dist-esm/decorators/memo.util.js +15 -1
  26. package/dist-esm/decorators/retry.decorator.js +2 -2
  27. package/dist-esm/index.js +3 -3
  28. package/dist-esm/json-schema/jsonSchemaBuilder.js +4 -4
  29. package/dist-esm/promise/AggregatedError.js +2 -7
  30. package/dist-esm/promise/pFilter.js +4 -4
  31. package/dist-esm/promise/pMap.js +79 -19
  32. package/dist-esm/promise/pRetry.js +70 -39
  33. package/package.json +1 -1
  34. package/src/decorators/asyncMemo.decorator.ts +151 -0
  35. package/src/decorators/memo.decorator.ts +16 -5
  36. package/src/decorators/memo.util.ts +49 -10
  37. package/src/decorators/retry.decorator.ts +2 -2
  38. package/src/error/error.model.ts +7 -0
  39. package/src/index.ts +5 -3
  40. package/src/json-schema/jsonSchemaBuilder.ts +4 -4
  41. package/src/promise/AggregatedError.ts +3 -8
  42. package/src/promise/pFilter.ts +5 -14
  43. package/src/promise/pMap.ts +72 -21
  44. package/src/promise/pRetry.ts +105 -41
  45. package/src/types.ts +5 -5
  46. package/dist/promise/pBatch.d.ts +0 -7
  47. package/dist/promise/pBatch.js +0 -30
  48. package/dist-esm/promise/pBatch.js +0 -23
  49. package/src/promise/pBatch.ts +0 -31
@@ -1,54 +1,85 @@
1
1
  import { _since, _stringifyAny } from '..';
2
+ import { TimeoutError } from './pTimeout';
2
3
  /**
3
4
  * Returns a Function (!), enhanced with retry capabilities.
4
5
  * Implements "Exponential back-off strategy" by multiplying the delay by `delayMultiplier` with each try.
5
6
  */
6
- // eslint-disable-next-line @typescript-eslint/ban-types
7
- export function pRetry(fn, opt = {}) {
8
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, name = fn.name, } = opt;
7
+ export function pRetryFn(fn, opt = {}) {
8
+ return async function pRetryFunction(...args) {
9
+ return await pRetry(() => fn.call(this, ...args), opt);
10
+ };
11
+ }
12
+ export async function pRetry(fn, opt = {}) {
13
+ const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, name, keepStackTrace = true, timeout, } = opt;
14
+ const fakeError = keepStackTrace ? new Error('RetryError') : undefined;
9
15
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt;
10
16
  if (opt.logAll) {
11
- logFirstAttempt = logRetries = logFailures = true;
17
+ logSuccess = logFirstAttempt = logRetries = logFailures = true;
12
18
  }
13
19
  if (opt.logNone) {
14
20
  logSuccess = logFirstAttempt = logRetries = logFailures = false;
15
21
  }
16
- const fname = ['pRetry', name].filter(Boolean).join('.');
17
- return async function (...args) {
18
- let delay = initialDelay;
19
- let attempt = 0;
20
- return await new Promise((resolve, reject) => {
21
- const next = async () => {
22
- const started = Date.now();
23
- try {
24
- attempt++;
25
- if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
26
- logger.log(`${fname} attempt #${attempt}...`);
27
- }
28
- const r = await fn.apply(this, args);
29
- if (logSuccess) {
30
- logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`);
31
- }
32
- resolve(r);
22
+ const fname = name || fn.name || 'pRetry function';
23
+ let delay = initialDelay;
24
+ let attempt = 0;
25
+ let timer;
26
+ let timedOut = false;
27
+ return await new Promise((resolve, reject) => {
28
+ const rejectWithTimeout = () => {
29
+ timedOut = true; // to prevent more tries
30
+ const err = new TimeoutError(`"${fname}" timed out after ${timeout} ms`);
31
+ if (fakeError) {
32
+ // keep original stack
33
+ err.stack = fakeError.stack.replace('Error: RetryError', 'TimeoutError');
34
+ }
35
+ reject(err);
36
+ };
37
+ const next = async () => {
38
+ if (timedOut)
39
+ return;
40
+ if (timeout) {
41
+ timer = setTimeout(rejectWithTimeout, timeout);
42
+ }
43
+ const started = Date.now();
44
+ try {
45
+ attempt++;
46
+ if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
47
+ logger.log(`${fname} attempt #${attempt}...`);
33
48
  }
34
- catch (err) {
35
- if (logFailures) {
36
- logger.warn(`${fname} attempt #${attempt} error in ${_since(started)}:`, _stringifyAny(err, {
37
- includeErrorData: true,
38
- }));
39
- }
40
- if (attempt >= maxAttempts || (predicate && !predicate(err, attempt, maxAttempts))) {
41
- // Give up
42
- reject(err);
43
- }
44
- else {
45
- // Retry after delay
46
- delay *= delayMultiplier;
47
- setTimeout(next, delay);
49
+ const r = await fn(attempt);
50
+ clearTimeout(timer);
51
+ if (logSuccess) {
52
+ logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`);
53
+ }
54
+ resolve(r);
55
+ }
56
+ catch (err) {
57
+ clearTimeout(timer);
58
+ if (logFailures) {
59
+ logger.warn(`${fname} attempt #${attempt} error in ${_since(started)}:`, _stringifyAny(err, {
60
+ includeErrorData: true,
61
+ }));
62
+ }
63
+ if (attempt >= maxAttempts ||
64
+ (predicate && !predicate(err, attempt, maxAttempts))) {
65
+ // Give up
66
+ if (fakeError) {
67
+ // Preserve the original call stack
68
+ Object.defineProperty(err, 'stack', {
69
+ value: err.stack +
70
+ '\n --' +
71
+ fakeError.stack.replace('Error: RetryError', ''),
72
+ });
48
73
  }
74
+ reject(err);
49
75
  }
50
- };
51
- void next();
52
- });
53
- };
76
+ else {
77
+ // Retry after delay
78
+ delay *= delayMultiplier;
79
+ setTimeout(next, delay);
80
+ }
81
+ }
82
+ };
83
+ void next();
84
+ });
54
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.80.0",
3
+ "version": "14.83.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
  }
@@ -3,18 +3,41 @@ import { _isPrimitive } from '../object/object.util'
3
3
  export type MemoSerializer = (args: any[]) => any
4
4
 
5
5
  export const jsonMemoSerializer: MemoSerializer = args => {
6
- if (!args.length) return undefined
6
+ if (args.length === 0) return undefined
7
7
  if (args.length === 1 && _isPrimitive(args[0])) return args[0]
8
8
  return JSON.stringify(args)
9
9
  }
10
10
 
11
- export interface MemoCache {
12
- has(k: any): boolean
13
- get(k: any): any
14
- set(k: any, v: any): void
11
+ export interface MemoCache<KEY = any, VALUE = any> {
12
+ has(k: KEY): boolean
13
+ get(k: KEY): VALUE | undefined
14
+ set(k: KEY, v: VALUE): void
15
+
16
+ /**
17
+ * Clear is only called when `.dropCache()` is called.
18
+ * Otherwise the Cache is "persistent" (never cleared).
19
+ */
15
20
  clear(): void
16
21
  }
17
22
 
23
+ export interface AsyncMemoCache<KEY = any, VALUE = any> {
24
+ // `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`
25
+ // has(k: any): Promise<boolean>
26
+ /**
27
+ * `undefined` value returned indicates the ABSENCE of value in the Cache.
28
+ * This also means that you CANNOT store `undefined` value in the Cache, as it'll be treated as a MISS.
29
+ * You CAN store `null` value instead, it will be treated as a HIT.
30
+ */
31
+ get(k: KEY): Promise<VALUE | undefined>
32
+ set(k: KEY, v: VALUE): Promise<void>
33
+
34
+ /**
35
+ * Clear is only called when `.dropCache()` is called.
36
+ * Otherwise the Cache is "persistent" (never cleared).
37
+ */
38
+ clear(): Promise<void>
39
+ }
40
+
18
41
  // SingleValueMemoCache and ObjectMemoCache are example-only, not used in production code
19
42
  /*
20
43
  export class SingleValueMemoCache implements MemoCache {
@@ -61,18 +84,18 @@ export class ObjectMemoCache implements MemoCache {
61
84
  }
62
85
  */
63
86
 
64
- export class MapMemoCache implements MemoCache {
65
- private m = new Map<any, any>()
87
+ export class MapMemoCache<KEY = any, VALUE = any> implements MemoCache<KEY, VALUE> {
88
+ private m = new Map<KEY, VALUE>()
66
89
 
67
- has(k: any): boolean {
90
+ has(k: KEY): boolean {
68
91
  return this.m.has(k)
69
92
  }
70
93
 
71
- get(k: any): any {
94
+ get(k: KEY): VALUE | undefined {
72
95
  return this.m.get(k)
73
96
  }
74
97
 
75
- set(k: any, v: any): void {
98
+ set(k: KEY, v: VALUE): void {
76
99
  this.m.set(k, v)
77
100
  }
78
101
 
@@ -80,3 +103,19 @@ export class MapMemoCache implements MemoCache {
80
103
  this.m.clear()
81
104
  }
82
105
  }
106
+
107
+ export class MapAsyncMemoCache<KEY = any, VALUE = any> implements AsyncMemoCache<KEY, VALUE> {
108
+ private m = new Map<KEY, VALUE>()
109
+
110
+ async get(k: KEY): Promise<VALUE | undefined> {
111
+ return this.m.get(k)
112
+ }
113
+
114
+ async set(k: KEY, v: VALUE): Promise<void> {
115
+ this.m.set(k, v)
116
+ }
117
+
118
+ async clear(): Promise<void> {
119
+ this.m.clear()
120
+ }
121
+ }
@@ -1,10 +1,10 @@
1
- import { pRetry, PRetryOptions } from '..'
1
+ import { pRetryFn, PRetryOptions } from '..'
2
2
 
3
3
  // eslint-disable-next-line @typescript-eslint/naming-convention
4
4
  export function _Retry(opt: PRetryOptions = {}): MethodDecorator {
5
5
  return (target, key, descriptor) => {
6
6
  const originalFn = descriptor.value
7
- descriptor.value = pRetry(originalFn as any, opt)
7
+ descriptor.value = pRetryFn(originalFn as any, opt)
8
8
  return descriptor
9
9
  }
10
10
  }
@@ -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
  */
package/src/index.ts CHANGED
@@ -12,7 +12,8 @@ export * from './decorators/debounce.decorator'
12
12
  export * from './decorators/decorator.util'
13
13
  export * from './decorators/logMethod.decorator'
14
14
  export * from './decorators/memo.decorator'
15
- import { MemoCache } from './decorators/memo.util'
15
+ export * from './decorators/asyncMemo.decorator'
16
+ import { MemoCache, AsyncMemoCache } from './decorators/memo.util'
16
17
  export * from './decorators/memoFn'
17
18
  export * from './decorators/retry.decorator'
18
19
  export * from './decorators/timeout.decorator'
@@ -67,14 +68,13 @@ export * from './object/object.util'
67
68
  export * from './object/sortObject'
68
69
  export * from './object/sortObjectDeep'
69
70
  import { AggregatedError } from './promise/AggregatedError'
70
- export * from './promise/pBatch'
71
71
  import { DeferredPromise, pDefer } from './promise/pDefer'
72
72
  export * from './promise/pDelay'
73
73
  export * from './promise/pFilter'
74
74
  export * from './promise/pHang'
75
75
  import { pMap, PMapOptions } from './promise/pMap'
76
76
  export * from './promise/pProps'
77
- import { pRetry, PRetryOptions } from './promise/pRetry'
77
+ import { pRetry, pRetryFn, PRetryOptions } from './promise/pRetry'
78
78
  export * from './promise/pState'
79
79
  import { pTimeout, pTimeoutFn, PTimeoutOptions } from './promise/pTimeout'
80
80
  export * from './promise/pTuple'
@@ -161,6 +161,7 @@ export type {
161
161
  AbortableAsyncMapper,
162
162
  PQueueCfg,
163
163
  MemoCache,
164
+ AsyncMemoCache,
164
165
  PromiseDecoratorCfg,
165
166
  PromiseDecoratorResp,
166
167
  ErrorData,
@@ -250,6 +251,7 @@ export {
250
251
  pDefer,
251
252
  AggregatedError,
252
253
  pRetry,
254
+ pRetryFn,
253
255
  pTimeout,
254
256
  pTimeoutFn,
255
257
  _tryCatch,
@@ -365,9 +365,9 @@ export class JsonSchemaObjectBuilder<T extends AnyObject> extends JsonSchemaAnyB
365
365
  return this
366
366
  }
367
367
 
368
- baseDBEntity(): JsonSchemaObjectBuilder<T & BaseDBEntity> {
368
+ baseDBEntity<ID = string>(idType = 'string'): JsonSchemaObjectBuilder<T & BaseDBEntity<ID>> {
369
369
  Object.assign(this.schema.properties, {
370
- id: { type: 'string' },
370
+ id: { type: idType },
371
371
  created: { type: 'number', format: 'unixTimestamp' },
372
372
  updated: { type: 'number', format: 'unixTimestamp' },
373
373
  })
@@ -375,8 +375,8 @@ export class JsonSchemaObjectBuilder<T extends AnyObject> extends JsonSchemaAnyB
375
375
  return this
376
376
  }
377
377
 
378
- savedDBEntity(): JsonSchemaObjectBuilder<T & SavedDBEntity> {
379
- return this.baseDBEntity().addRequired(['id', 'created', 'updated']) as any
378
+ savedDBEntity<ID = string>(idType = 'string'): JsonSchemaObjectBuilder<T & SavedDBEntity<ID>> {
379
+ return this.baseDBEntity(idType).addRequired(['id', 'created', 'updated']) as any
380
380
  }
381
381
 
382
382
  extend<T2 extends AnyObject>(s2: JsonSchemaObjectBuilder<T2>): JsonSchemaObjectBuilder<T & T2> {
@@ -7,20 +7,15 @@ export class AggregatedError<RESULT = any> extends Error {
7
7
  errors!: Error[]
8
8
  results!: RESULT[]
9
9
 
10
- constructor(errors: (Error | string)[], results: RESULT[] = []) {
11
- const mappedErrors = errors.map(e => {
12
- if (typeof e === 'string') return new Error(e)
13
- return e
14
- })
15
-
10
+ constructor(errors: Error[], results: RESULT[] = []) {
16
11
  const message = [
17
12
  `${errors.length} errors:`,
18
- ...mappedErrors.map((e, i) => `${i + 1}. ${e.message}`),
13
+ ...errors.map((e, i) => `${i + 1}. ${e.message}`),
19
14
  ].join('\n')
20
15
 
21
16
  super(message)
22
17
 
23
- this.errors = mappedErrors
18
+ this.errors = errors
24
19
  this.results = results
25
20
 
26
21
  Object.defineProperty(this, 'name', {
@@ -1,16 +1,7 @@
1
- import { AbortableAsyncPredicate } from '../types'
2
- import { pMap, PMapOptions } from './pMap'
1
+ import { AsyncPredicate } from '../types'
3
2
 
4
- export async function pFilter<T>(
5
- iterable: Iterable<T | PromiseLike<T>>,
6
- filterFn: AbortableAsyncPredicate<T>,
7
- opt?: PMapOptions,
8
- ): Promise<T[]> {
9
- const values = await pMap(
10
- iterable,
11
- async (item, index) => await Promise.all([filterFn(item, index), item]),
12
- opt,
13
- )
14
-
15
- return values.filter(value => Boolean(value[0])).map(value => value[1])
3
+ export async function pFilter<T>(iterable: Iterable<T>, filterFn: AsyncPredicate<T>): Promise<T[]> {
4
+ const items = [...iterable]
5
+ const predicates = await Promise.all(items.map((item, i) => filterFn(item, i)))
6
+ return items.filter((item, i) => predicates[i])
16
7
  }