UNPKG

1.94 kBPlain TextView Raw
1import { Lambda } from 'aws-sdk';
2
3const lambda = new Lambda({ region: 'us-east-1' });
4
5/**
6 * Invokes the function and returns the parsed body
7 * @param {[type]} functionName [description]
8 * @param {[type]} body [description]
9 * @return {[type]} [description]
10 */
11export 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 * Invokes the event
23 * @param {[type]} functionName [description]
24 * @param {[type]} body [description]
25 * @return {[type]} [description]
26 */
27export 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
40function 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
49function 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 // errors will be serialized with errorMessage, errorType, and stack properties
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}