-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.js
54 lines (42 loc) · 1.35 KB
/
lib.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
const Request = require('./Request');
const Response = require('./Response');
const stack = [];
const handle = (name, middlewares, controller) => async (event, context) => {
// Middlewares are optional to have the same interface like express
if (!controller) {
controller = middlewares;
middlewares = [];
}
const req = new Request(event);
const res = new Response(context);
// We need to clone the array used by all handle
let stackWithController = stack.slice(0);
// Add the controller specific middlewares
if (Array.isArray(middlewares)) {
stackWithController = stackWithController.concat(middlewares);
} else {
stackWithController.push(middlewares);
}
// A controller is also a middleware
stackWithController.push(async (req, res, next) => controller(req, res));
// Index for the current middleware
let idx = -1;
async function next(err) {
if (err) {
throw err;
}
// We can never overflow due the fact that the controller is not calling next()
++idx;
await stackWithController[idx](req, res, next);
}
// The central try/catch sending the error preventing unhandled errors
try {
await next();
} catch (err) {
res.status(400).send(err);
}
// Always finalize the lambda at the end
res.end();
};
const use = middleware => stack.push(middleware);
module.exports = { handle, use };