-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathintegration.js
79 lines (67 loc) · 2.03 KB
/
integration.js
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
const promisify = require('util').promisify;
const AWS = require('aws-sdk');
const debug = require('debug')('express-gateway-plugin-lambda:integration');
const fileType = require('file-type');
class Integration {
constructor({ req, res, requestBody, settings }) {
this.req = req;
this.res = res;
this.requestBody = requestBody;
this.settings = settings;
}
guessContentType(body, isBase64Encoded) {
const type = fileType(Buffer.from(body, 'base64'));
if (isBase64Encoded) {
if (type && type.mime) {
return type.mime
} else {
return 'application/octet-stream';
}
} else {
if (type && type.mime) {
return type.mime
} else if (body.length > this.settings.maxJSONParseLength) {
// performance penalty on JSON.parse for large content lengths
return 'text/plain';
} else {
try {
const _ = JSON.parse(body.toString());
return 'application/json';
} catch (_) {
return 'text/plain';
}
}
}
}
invoke() {
const lambda = new AWS.Lambda();
const invoke = promisify(lambda.invoke.bind(lambda));
const settings = this.settings;
const res = this.res;
const functionOptions = this.build();
return invoke(functionOptions).then(data => {
if (data.FunctionError) {
if (data.FunctionError === 'Unhandled') {
res.statusCode = settings.unhandledStatus;
} else {
res.statusCode = data.StatusCode;
}
debug(`Failed to execute Lambda function (${data.FunctionError}):`,
JSON.parse(data.Payload).errorMessage);
res.end();
return;
}
this.respond(data.Payload);
})
.catch(ex => {
debug(ex);
this.res.sendStatus(500);
});
}
get isRequestBodyBinary() {
return this.req.isBinary
|| !!fileType(this.requestBody)
|| (this.req.headers['content-type'] && this.req.headers['content-type'] === 'application/octet-stream');
}
}
module.exports = { Integration };