-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
69 lines (62 loc) · 2.25 KB
/
index.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
/**
* Written in Javascript due to ease of parsing JSON
* Might re-write in Typescript later on.
*/
const swaggerJSDoc = require('swagger-jsdoc');
const {
parseSwaggerRouteData,
writeAsSwaggerDocToFile,
debugLogger,
replaceRoutes,
} = require('@tiemma/sonic-core');
const logger = debugLogger(__filename);
const parameterRegex = /(:\w+\??)/g;
const normalizePath = (path) => (path[path.length - 1] === '/' ? path.substr(0, path.length - 1) : path);
const getResponseExpress = (app, swaggerOptions, swaggerFilePath) => {
// Set state of swaggerSpec on first request
// Update and write in-memory spec to file
const swaggerSpec = swaggerOptions ? swaggerJSDoc(swaggerOptions) : {};
const { definitionMap } = swaggerOptions ? parseSwaggerRouteData(swaggerSpec, {}) : {};
const serverUrls = swaggerOptions ? swaggerSpec.servers.map((x) => x.url) : [];
const domainsRegex = new RegExp(`(${serverUrls.join('|')})`);
logger('Sonic middleware initiated');
return (req, res, next) => {
const { send } = res;
// eslint-disable-next-line func-names
res.send = function (responseBody) {
const domain = req.baseUrl.split(domainsRegex).slice(2);
if (domain.length > 0) {
const originalRoute = res.req.route
? domain.join('/') + res.req.route.path
: req.url;
const { method } = res.req;
let definitionName;
const route = replaceRoutes(originalRoute, parameterRegex);
if (
definitionMap[route]
&& definitionMap[route][method]
) {
definitionName = definitionMap[route][method];
}
const { body: requestBody, query: queries } = res.req;
const contentType = (res.get('Content-Type') || 'text/html').split(';')[0];
const { statusCode } = res;
writeAsSwaggerDocToFile(swaggerSpec,
method.toLowerCase(),
normalizePath(originalRoute),
parameterRegex,
responseBody,
requestBody,
queries,
statusCode,
contentType,
definitionName,
swaggerFilePath);
}
// eslint-disable-next-line prefer-rest-params
return send.apply(this, arguments);
};
return next();
};
};
module.exports = { getResponseExpress };