This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
router.js
92 lines (76 loc) · 2.88 KB
/
router.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
80
81
82
83
84
85
86
87
88
89
90
91
92
module.exports = require('injectdeps')(['container', 'logger'], function(container, logger) {
return params => {
params = params || {};
const log = logger('swagger');
return (req, res, next) => {
const methodAndPath = `${req.method} ${req.path}`;
// First check if the path is supported by our swagger definition
// Note that we're assuming that another module has checked this and decorated the request object
// The basic implementation is the swagger-tools/metadata middleware exposed through the tools module
if(!req.swagger || !req.swagger.operation) {
let err = new Error(`Unsupported endpoint ${methodAndPath}`);
err.statusCode = 404;
return next(err);
}
const controllerName = req.swagger.path['x-swagger-router-controller'];
if(!controllerName) {
return next(new Error(`Swagger specification does not specify a controller for ${methodAndPath}`));
}
const fullControllerName = (params.prefix || '') + controllerName;
if(!container.hasObject(fullControllerName)) {
return next(new Error(`Could not find controller ${fullControllerName}`));
}
let controller;
try {
controller = container.getObject(fullControllerName);
}
catch(err) {
return next(err);
}
const methodName = req.swagger.operation.operationId;
if(!methodName) {
return next(new Error(`Swagger specification does not specify an operationId for ${methodAndPath}`));
}
log.debug('Forwarding request %s to %s.%s', methodAndPath, controllerName, methodName);
if(!controller.hasOwnProperty(methodName) || typeof controller[methodName] !== 'function'){
return next(new Error(`Controller ${fullControllerName} doesn't handle operation ${methodName}`));
}
const nextHandler = (maybeError) => {
if(maybeError) {
next(maybeError);
}
next(); // always call next
};
const fakeResponse = {
status(code) {
return res.status(code);
},
json(returnedObject) {
return res.contentType('application/json').json(returnedObject);
}
};
try {
const handlerResponse = controller[methodName](req, fakeResponse, nextHandler);
if(typeof handlerResponse !== 'undefined') {
if(handlerResponse.then && typeof handlerResponse.then === 'function') {
handlerResponse.then(result => {
res.json(result);
next();
});
if(handlerResponse.catch && typeof handlerResponse.catch === 'function') {
handlerResponse.catch(next);
}
}
else {
res.json(handlerResponse);
next();
}
}
}
catch (err) {
// catch unhandled errors
return next(err);
}
};
};
});