-
Notifications
You must be signed in to change notification settings - Fork 819
/
execute.ts
104 lines (93 loc) · 2.55 KB
/
execute.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { existsSync } from 'fs-extra';
import _ = require('lodash');
const path = require('path');
function loadFunction(fileName) {
return require(path.resolve(fileName));
}
type InvokeOptions = {
packageFolder: string;
handler: string;
fileName: string;
event: string;
context?: object;
};
function invokeFunction(options: InvokeOptions) {
return new Promise(async (resolve, reject) => {
let returned = false;
const context = {
done(error, result) {
if (!returned) {
returned = true;
if (error === null || typeof error === 'undefined') {
context.succeed(result);
} else {
context.fail(error);
}
}
},
succeed(result) {
returned = true;
resolve(result);
},
fail(error) {
returned = true;
reject(_.assign({}, error));
},
awsRequestId: 'LAMBDA_INVOKE',
logStreamName: 'LAMBDA_INVOKE',
};
if (options.packageFolder) {
const p = path.resolve(options.packageFolder);
if (!existsSync(p)) {
context.fail('packageFolder does not exist');
return;
}
process.chdir(p);
} else {
context.fail('packageFolder is not defined');
return;
}
if (!options.handler) {
context.fail('handler is not defined');
return;
}
if (options.context) {
Object.assign(context, options.context);
}
const callback = (error, object) => {
context.done(error, object);
};
const lambda = loadFunction(options.fileName);
const { event } = options;
try {
if (!lambda[options.handler]) {
context.fail(
`handler ${options.handler} does not exist in the lambda function ${path.join(options.packageFolder, options.fileName)}`,
);
return;
}
const response = lambda[options.handler](event, context, callback);
if (typeof response === 'object' && typeof response.then === 'function') {
const result = await response;
if (result !== undefined) {
context.done(null, result);
} else {
context.done(null, null);
}
} else if (response !== undefined) {
context.done(null, null);
}
} catch (e) {
context.done(e, null);
}
});
}
process.on('message', async options => {
try {
const result = await invokeFunction(JSON.parse(options));
process.send(JSON.stringify({ result, error: null }));
} catch (error) {
process.send(JSON.stringify({ result: null, error }));
}
process.exit(1);
});