forked from dougmoscrop/serverless-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverless-http.js
63 lines (51 loc) · 1.56 KB
/
serverless-http.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
'use strict';
const finish = require('./lib/finish');
const sanitizeHeaders = require('./lib/sanitize-headers');
const getHandler = require('./lib/get-handler');
const Request = require('./lib/request');
const Response = require('./lib/response');
const defaultOptions = {
requestId: 'x-request-id'
};
module.exports = function(app, opts) {
const handler = getHandler(app);
const options = Object.assign({}, defaultOptions, opts);
return (evt, ctx, callback) => {
Promise.resolve()
.then(() => {
const context = ctx || {};
const event = cleanupEvent(evt);
const request = new Request(event, options);
return finish(request, event, context, options.request)
.then(() => {
const response = new Response(request);
handler(request, response);
return finish(response, event, context, options.response);
});
})
.then(res => {
process.nextTick(() => {
callback(null, {
statusCode: res.statusCode,
headers: sanitizeHeaders(res._headers),
body: res._body
});
});
})
.catch(e => {
process.nextTick(() => {
callback(e);
});
});
};
};
function cleanupEvent(evt) {
const event = evt || {};
event.httpMethod = event.httpMethod || 'GET';
event.path = event.path || '/';
event.body = event.body || '';
event.headers = event.headers || {};
event.requestContext = event.requestContext || {};
event.requestContext.identity = event.requestContext.identity || {};
return event;
}