forked from mpashkovskiy/express-oas-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
198 lines (172 loc) · 5.34 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const swaggerUi = require('swagger-ui-express');
const utils = require('./lib/utils');
const processors = require('./lib/processors');
const listEndpoints = require('express-list-endpoints');
let packageJsonPath = `${process.cwd()}/package.json`;
let packageInfo;
let app;
let predefinedSpec;
let spec = {};
let lastRecordTime = new Date().getTime();
function updateSpecFromPackage() {
/* eslint global-require : off */
packageInfo = fs.existsSync(packageJsonPath) ? require(packageJsonPath) : {};
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 };
}
if (packageInfo.baseUrlPath) {
spec.info.description = '[Specification JSON](' + packageInfo.baseUrlPath + '/api-spec) , base url : ' + packageInfo.baseUrlPath;
} else {
packageInfo.baseUrlPath = '';
spec.info.description = '[Specification JSON](' + packageInfo.baseUrlPath + '/api-spec)';
}
if (packageInfo.description) {
spec.info.description += `\n\n${packageInfo.description}`;
}
}
function init(aApiDocsPath) {
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,
})) || [],
responses: {}
};
});
});
updateSpecFromPackage();
spec = patchSpec(predefinedSpec);
app.use(packageInfo.baseUrlPath + '/api-spec', (req, res, next) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(patchSpec(predefinedSpec), null, 2));
next();
});
app.use(packageInfo.baseUrlPath + '/' + aApiDocsPath, swaggerUi.serve, (req, res) => {
swaggerUi.setup(patchSpec(predefinedSpec))(req, res);
});
}
function patchSpec(predefinedSpec) {
return typeof predefinedSpec === 'object'
? utils.sortObject(_.merge(spec, predefinedSpec || {}))
: predefinedSpec(spec);
}
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, aPredefinedSpec, aPath, aWriteInterval, aApiDocsPath = 'api-docs') => {
app = aApp;
predefinedSpec = aPredefinedSpec;
const writeInterval = aWriteInterval | 10 * 1000;
// middleware to handle responses
app.use((req, res, next) => {
try {
const methodAndPathKey = getMethod(req);
if (methodAndPathKey && methodAndPathKey.method) {
processors.processResponse(res, methodAndPathKey.method);
}
const ts = new Date().getTime();
if (aPath && ts - lastRecordTime > writeInterval) {
lastRecordTime = ts;
fs.writeFile(aPath, JSON.stringify(spec, null, 2), 'utf8', err => {
const fullPath = path.resolve(aPath);
if (err) {
throw new Error(`Cannot store the specification into ${fullPath} because of ${err.message}`);
}
});
}
} catch (e) {}
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);
}
} catch (e) {}
next();
});
init(aApiDocsPath);
}, 1000);
};
module.exports.getSpec = () => {
return patchSpec(predefinedSpec);
};
module.exports.setPackageInfoPath = pkgInfoPath => {
packageJsonPath = `${process.cwd()}/${pkgInfoPath}/package.json`;
};