forked from mpashkovskiy/express-oas-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
162 lines (141 loc) · 4.05 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
const _ = require('lodash');
const fs = require('fs');
const swaggerUi = require('swagger-ui-express');
const utils = require('./lib/utils');
const processors = require('./lib/processors');
const listEndpoints = require('express-list-endpoints');
const packageJsonPath = `${process.cwd()}/package.json`;
const packageInfo = fs.existsSync(packageJsonPath) ? require(packageJsonPath) : {};
let app;
let spec = {};
function updateSpecFromPackage() {
spec.info = spec.info || {};
if (packageInfo.name) {
spec.info.title = packageInfo.name;
}
if (packageInfo.version) {
spec.info.version = packageInfo.version;
}
if (packageInfo.license) {
spec.info.license = { name: packageInfo.license };
}
spec.info.description = '[Specification JSON](/api-spec)';
if (packageInfo.description) {
spec.info.description += `\n\n${packageInfo.description}`;
}
}
function init(predefinedSpec) {
spec = { swagger: '2.0', paths: {} };
const endpoints = listEndpoints(app);
endpoints.forEach(endpoint => {
const params = [];
let path = endpoint.path;
const matches = path.match(/:([^/]+)/g);
if (matches) {
matches.forEach(found => {
const paramName = found.substr(1);
path = path.replace(found, `{${paramName}}`);
params.push(paramName);
});
}
if (!spec.paths[path]) {
spec.paths[path] = {};
}
endpoint.methods.forEach(m => {
spec.paths[path][m.toLowerCase()] = {
summary: path,
consumes: ['application/json'],
parameters: params.map(p => ({
name: p,
in: 'path',
required: true,
})) || [],
};
});
});
updateSpecFromPackage();
spec = utils.sortObject(_.merge(spec, predefinedSpec || {}));
app.use('/api-spec', (req, res, next) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(spec, null, 2));
return next();
});
app.use('/api-docs', swaggerUi.serve, (req, res) => {
swaggerUi.setup(spec)(req, res);
});
}
function getPathKey(req) {
if (!req.url) {
return undefined;
}
if (spec.paths[req.url]) {
return req.url;
}
const url = req.url.split('?')[0];
const pathKeys = Object.keys(spec.paths);
for (let i = 0; i < pathKeys.length; i += 1) {
const pathKey = pathKeys[i];
if (url.match(`${pathKey.replace(/{([^/]+)}/g, '(?:([^\\\\/]+?))')}/?$`)) {
return pathKey;
}
}
return undefined;
}
function getMethod(req) {
if (req.url.startsWith('/api-')) {
return undefined;
}
const m = req.method.toLowerCase();
if (m === 'options') {
return undefined;
}
const pathKey = getPathKey(req);
if (!pathKey) {
return undefined;
}
return { method: spec.paths[pathKey][m], pathKey };
}
function updateSchemesAndHost(req) {
spec.schemes = spec.schemes || [];
if (spec.schemes.indexOf(req.protocol) === -1) {
spec.schemes.push(req.protocol);
}
if (!spec.host) {
spec.host = req.get('host');
}
}
module.exports.init = (aApp, predefinedSpec) => {
app = aApp;
// middleware to handle responses
app.use((req, res, next) => {
try {
const methodAndPathKey = getMethod(req);
if (methodAndPathKey && methodAndPathKey.method) {
processors.processResponse(res, methodAndPathKey.method);
}
} finally {
return next();
}
});
// make sure we list routes after they are configured
setTimeout(() => {
// middleware to handle requests
app.use((req, res, next) => {
try {
const methodAndPathKey = getMethod(req);
if (methodAndPathKey && methodAndPathKey.method && methodAndPathKey.pathKey) {
const method = methodAndPathKey.method;
updateSchemesAndHost(req);
processors.processPath(req, method, methodAndPathKey.pathKey);
processors.processHeaders(req, method, spec);
processors.processBody(req, method);
processors.processQuery(req, method);
}
} finally {
return next();
}
});
init(predefinedSpec);
}, 1000);
};
module.exports.getSpec = () => spec;