1 | import { Lambda } from 'aws-sdk';
|
2 |
|
3 | const lambda = new Lambda({ region: 'us-east-1' });
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | export async function invoke<T>(functionName: string, body: object | string): Promise<T> {
|
12 | return lambda
|
13 | .invoke({
|
14 | FunctionName: functionName,
|
15 | Payload: createPayload(body),
|
16 | })
|
17 | .promise()
|
18 | .then(data => parseResponse<T>(functionName, data));
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | export async function invokeEvent(functionName: string, body: object | string): Promise<boolean> {
|
28 | return lambda
|
29 | .invoke({
|
30 | FunctionName: functionName,
|
31 | InvocationType: 'Event',
|
32 | Payload: createPayload(body),
|
33 | })
|
34 | .promise()
|
35 | .then(data => data.StatusCode === 200);
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 | function createPayload(body: object | string): string {
|
41 | if (body === undefined) return undefined;
|
42 | else if (typeof body === 'string') {
|
43 | return body;
|
44 | } else if (typeof body === 'object') {
|
45 | return JSON.stringify(body);
|
46 | }
|
47 | }
|
48 |
|
49 | function parseResponse<T>(functionName: string, res: Lambda.InvocationResponse): any {
|
50 | let result;
|
51 | if (res.StatusCode === 200) {
|
52 | result = JSON.parse(res.Payload.toString());
|
53 | }
|
54 |
|
55 | if (!result) {
|
56 | return;
|
57 | }
|
58 |
|
59 |
|
60 | if (result.errorMessage) {
|
61 | let error = new Error(`Invocation of ${functionName} failed.`);
|
62 | console.log(result);
|
63 | error.stack = result.stack;
|
64 | throw error;
|
65 | } else {
|
66 | return result;
|
67 | }
|
68 | }
|