-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathinvokeTestFunction.ts
87 lines (77 loc) · 2.51 KB
/
invokeTestFunction.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda';
import { fromUtf8 } from '@smithy/util-utf8';
import { TestInvocationLogs } from './TestInvocationLogs.js';
import type { InvokeTestFunctionOptions } from './types.js';
const lambdaClient = new LambdaClient({});
/**
* Invoke a Lambda function once and return the logs
*/
const invokeFunctionOnce = async ({
functionName,
payload = {},
}: Omit<
InvokeTestFunctionOptions,
'times' | 'invocationMode'
>): Promise<TestInvocationLogs> => {
const result = await lambdaClient.send(
new InvokeCommand({
FunctionName: functionName,
InvocationType: 'RequestResponse',
LogType: 'Tail', // Wait until execution completes and return all logs
Payload: fromUtf8(JSON.stringify(payload)),
})
);
if (result?.LogResult) {
return new TestInvocationLogs(result?.LogResult);
}
throw new Error(
'No LogResult field returned in the response of Lambda invocation. This should not happen.'
);
};
/**
* Invoke a Lambda function multiple times and return the logs
*
* When specifying a payload, you can either pass a single object that will be used for all invocations,
* or an array of objects that will be used for each invocation. If you pass an array, the length of the
* array must be the same as the times parameter.
*/
const invokeFunction = async ({
functionName,
times = 1,
invocationMode = 'PARALLEL',
payload = {},
}: InvokeTestFunctionOptions): Promise<TestInvocationLogs[]> => {
const invocationLogs: TestInvocationLogs[] = [];
if (payload && Array.isArray(payload) && payload.length !== times) {
throw new Error(
'The payload array must have the same length as the times parameter.'
);
}
if (invocationMode === 'PARALLEL') {
const invocationPromises = Array.from(
{ length: times },
() => invokeFunctionOnce
);
invocationLogs.push(
...(await Promise.all(
invocationPromises.map((invoke, index) => {
const invocationPayload = Array.isArray(payload)
? payload[index]
: payload;
return invoke({ functionName, payload: invocationPayload });
})
))
);
} else {
for (let index = 0; index < times; index++) {
const invocationPayload = Array.isArray(payload)
? payload[index]
: payload;
invocationLogs.push(
await invokeFunctionOnce({ functionName, payload: invocationPayload })
);
}
}
return invocationLogs;
};
export { invokeFunctionOnce, invokeFunction };