-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathmakeFunctionIdempotent.ts
58 lines (51 loc) · 1.64 KB
/
makeFunctionIdempotent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type { Context } from 'aws-lambda';
import type {
AnyFunctionWithRecord,
AnyIdempotentFunction,
IdempotencyFunctionOptions,
} from './types';
import { IdempotencyHandler } from './IdempotencyHandler';
import { IdempotencyConfig } from './IdempotencyConfig';
const isContext = (arg: unknown): arg is Context => {
return (
arg !== undefined &&
arg !== null &&
typeof arg === 'object' &&
'getRemainingTimeInMillis' in arg
);
};
const makeFunctionIdempotent = function <U>(
fn: AnyFunctionWithRecord<U>,
options: IdempotencyFunctionOptions
): AnyIdempotentFunction<U> | AnyFunctionWithRecord<U> {
const idempotencyConfig = options.config
? options.config
: new IdempotencyConfig({});
const wrappedFn: AnyIdempotentFunction<U> = function (
...args: Parameters<AnyFunctionWithRecord<U>>
): Promise<U> {
const payload = args[0];
const context = args[1];
if (options.dataKeywordArgument === undefined) {
throw new Error(
`Missing data keyword argument ${options.dataKeywordArgument}`
);
}
if (isContext(context)) {
idempotencyConfig.registerLambdaContext(context);
}
const idempotencyHandler: IdempotencyHandler<U> = new IdempotencyHandler<U>(
{
functionToMakeIdempotent: fn,
functionPayloadToBeHashed: payload[options.dataKeywordArgument],
idempotencyConfig: idempotencyConfig,
persistenceStore: options.persistenceStore,
fullFunctionPayload: payload,
}
);
return idempotencyHandler.handle();
};
if (idempotencyConfig.isEnabled()) return wrappedFn;
else return fn;
};
export { makeFunctionIdempotent };