-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.js
543 lines (466 loc) · 14.6 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/**
* @fileOverview main file
* @module index
*/
require('./index');
const _merge = require('lodash.merge');
const fs = require('fs');
const path = require('path');
const swaggerUi = require('swagger-ui-express');
const utils = require('./lib/utils');
const { generateMongooseModelsSpec } = require('./lib/mongoose');
const { generateTagsSpec, matchingTags } = require('./lib/tags');
const { convertOpenApiVersionToV3, getSpecByVersion, versions } = require('./lib/openapi');
const processors = require('./lib/processors');
const listEndpoints = require('express-list-endpoints');
const { logger } = require('./lib/logger');
const { ensureDirectoryExistence } = require('./lib/file');
const SPEC_OUTPUT_FILE_BEHAVIOR = {
PRESERVE: 'PRESERVE',
RECREATE: 'RECREATE'
};
const DEFAULT_SWAGGER_UI_SERVE_PATH = 'api-docs';
const DEFAULT_IGNORE_NODE_ENVIRONMENTS = ['production'];
const UNDEFINED_NODE_ENV_ERROR = ignoredNodeEnvironments => `WARNING!!! process.env.NODE_ENV is not defined.\
To disable the module set process.env.NODE_ENV to any of the supplied ignoredNodeEnvironments: ${ignoredNodeEnvironments.join()}`;
const WRONG_MIDDLEWARE_ORDER_ERROR = `
Express oas generator:
you miss-placed the **response** and **request** middlewares!
Please, make sure to:
1. place the RESPONSE middleware FIRST,
right after initializing the express app,
2. and place the REQUEST middleware LAST,
inside the app.listen callback
For more information, see https://github.com/mpashkovskiy/express-oas-generator#Advanced-usage-recommended
`;
let packageJsonPath = `${process.cwd()}/package.json`;
let packageInfo;
let app;
/**
* @param {function|object} predefinedSpec either the Swagger specification
* or a function with one argument producing it.
*/
let swaggerUiServePath;
let predefinedSpec;
let spec = {};
let mongooseModelsSpecs;
let tagsSpecs;
let ignoredNodeEnvironments;
let serveDocs;
let specOutputPath;
let specOutputFileBehavior;
/**
* @type { typeof import('./index').SwaggerUiOptions }
*/
let swaggerDocumentOptions;
/**
* @param {boolean} [responseMiddlewareHasBeenApplied=false]
*
* @note make sure to reset this variable once you've done your checks.
*
* @description used make sure the *order* of which the middlewares are applied is correct
*
* The `response` middleware MUST be applied FIRST,
* before the `request` middleware is applied.
*
* We'll use this to make sure the order is correct.
* If not - we'll throw an informative error.
*/
let responseMiddlewareHasBeenApplied = false;
/**
*
*/
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 };
}
packageInfo.baseUrlPath = packageInfo.baseUrlPath || '';
const v2link = `[${versions.OPEN_API_V2}](${packageInfo.baseUrlPath}/api-spec/${versions.OPEN_API_V2})`;
const v3link = `[${versions.OPEN_API_V3}](${packageInfo.baseUrlPath}/api-spec/${versions.OPEN_API_V3})`;
spec.info.description = `Specification JSONs: ${v2link}, ${v3link}.`;
if (packageInfo.baseUrlPath !== '') {
spec.basePath = packageInfo.baseUrlPath;
spec.info.description += ` Base url: [${packageInfo.baseUrlPath}](${packageInfo.baseUrlPath})`;
}
if (packageInfo.description) {
spec.info.description += `\n\n${packageInfo.description}`;
}
}
/**
* @description Builds api spec middleware
*
* @returns Middleware
*/
function apiSpecMiddleware(version) {
return (req, res) => {
getSpecByVersion(spec, version, (err, openApiSpec) => {
if (!err) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(openApiSpec, null, 2));
}
});
};
}
/**
* @description Builds swagger serve middleware
* @param version Available open api versions: 'v2' (default if empty) or 'v3'.
* @returns Middleware
*/
function swaggerServeMiddleware(version) {
return (req, res) => {
getSpecByVersion(spec, version, (err, openApiSpec) => {
if (!err) {
res.setHeader('Content-Type', 'text/html');
swaggerUi.setup(openApiSpec, swaggerDocumentOptions)(req, res);
}
});
};
}
/**
* @description Applies spec middlewares
* @param version Available open api versions: 'v2' (default if empty) or 'v3'.
*/
function applySpecMiddlewares(version = '') {
const apiSpecBasePath = packageInfo.baseUrlPath.concat('/api-spec');
const baseSwaggerServePath = packageInfo.baseUrlPath.concat('/' + swaggerUiServePath);
app.use(apiSpecBasePath.concat('/' + version), apiSpecMiddleware(version));
app.use(baseSwaggerServePath.concat('/' + version), swaggerUi.serve, swaggerServeMiddleware(version));
}
/**
* @description Prepares spec to be served
*
* @returns void
*/
function prepareSpec() {
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] = {};
}
spec.tags = tagsSpecs || [];
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: {},
tags: matchingTags(tagsSpecs || [], path)
};
});
});
spec.definitions = mongooseModelsSpecs || {};
updateSpecFromPackage();
spec = patchSpec(predefinedSpec);
}
/**
* @description serve the openAPI docs with swagger at a specified path / url
*
* @returns void
*/
function serveApiDocs() {
prepareSpec();
applySpecMiddlewares(versions.OPEN_API_V2);
applySpecMiddlewares(versions.OPEN_API_V3);
// Base path middleware should be applied after specific versions
applySpecMiddlewares();
}
/**
*
* @param predefinedSpec
* @returns {{}}
*/
function patchSpec(predefinedSpec) {
return !predefinedSpec
? spec
: typeof predefinedSpec === 'object'
? utils.sortObject(_merge(spec, predefinedSpec || {}))
: predefinedSpec(spec);
}
/**
*
* @param req
* @returns {string|undefined|*}
*/
function getPathKey(req) {
if (!req.url || 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;
}
/**
*
* @param req
* @returns {{method: *, pathKey: *}|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 };
}
/**
*
* @param req
*/
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');
}
}
/**
* @description Generates definitions spec from mongoose models
*/
function updateDefinitionsSpec(mongooseModels) {
const validMongooseModels = Array.isArray(mongooseModels) && mongooseModels.length > 0;
if (validMongooseModels && !mongooseModelsSpecs) {
mongooseModelsSpecs = generateMongooseModelsSpec(mongooseModels);
}
}
/**
* @description Generates tags spec
*/
function updateTagsSpec(tags) {
const validTags = tags && Array.isArray(tags) && tags.length > 0;
if (validTags && !tagsSpecs) {
tagsSpecs = generateTagsSpec(tags);
}
}
/**
* @description Loads specOutputPath initial content to predefinedSpec.
* Based on SPEC_OUTPUT_FILE_BEHAVIOR.PRESERVE or SPEC_OUTPUT_FILE_BEHAVIOR.RECREATE
*/
function loadSpecOutputPathContent() {
if (specOutputFileBehavior !== SPEC_OUTPUT_FILE_BEHAVIOR.PRESERVE) {
return;
}
if (!fs.existsSync(specOutputPath)) {
return;
}
const specOutputFileContent = fs.readFileSync(specOutputPath).toString();
predefinedSpec = JSON.parse(specOutputFileContent);
}
/**
* @description Persists OpenAPI content to spec output file
*/
function writeSpecToOutputFile() {
if (!specOutputPath) {
return;
}
fs.writeFileSync(specOutputPath, JSON.stringify(spec, null, 2), 'utf8');
convertOpenApiVersionToV3(spec, (err, specV3) => {
if (!err) {
const parsedSpecOutputPath = path.parse(specOutputPath);
const {name, ext} = parsedSpecOutputPath;
parsedSpecOutputPath.base = name.concat('_').concat(versions.OPEN_API_V3).concat(ext);
const v3Path = path.format(parsedSpecOutputPath);
fs.writeFileSync(v3Path, JSON.stringify(specV3, null, 2), 'utf8');
}
/** TODO - Log that open api v3 could not be generated */
});
}
/**
* @type { typeof import('./index').handleResponses }
*/
function handleResponses(expressApp,
options = {
swaggerUiServePath: DEFAULT_SWAGGER_UI_SERVE_PATH,
specOutputPath: undefined,
predefinedSpec: {},
writeIntervalMs: 0,
mongooseModels: [],
tags: undefined,
ignoredNodeEnvironments: DEFAULT_IGNORE_NODE_ENVIRONMENTS,
alwaysServeDocs: undefined,
specOutputFileBehavior: SPEC_OUTPUT_FILE_BEHAVIOR.RECREATE,
swaggerDocumentOptions: {}
}) {
ignoredNodeEnvironments = options.ignoredNodeEnvironments || DEFAULT_IGNORE_NODE_ENVIRONMENTS;
const isEnvironmentIgnored = ignoredNodeEnvironments.includes(process.env.NODE_ENV || '');
serveDocs = options.alwaysServeDocs;
if (serveDocs === undefined) {
serveDocs = !isEnvironmentIgnored;
}
if (!process.env.NODE_ENV) {
logger.warn(UNDEFINED_NODE_ENV_ERROR(ignoredNodeEnvironments));
}
/**
* save the `expressApp` to our local `app` variable.
* Used here, but not in `handleRequests`,
* because this comes before it.
*/
app = expressApp;
swaggerUiServePath = options.swaggerUiServePath || DEFAULT_SWAGGER_UI_SERVE_PATH;
predefinedSpec = options.predefinedSpec || {};
specOutputPath = options.specOutputPath;
specOutputFileBehavior = options.specOutputFileBehavior;
swaggerDocumentOptions = options.swaggerDocumentOptions;
loadSpecOutputPathContent();
updateDefinitionsSpec(options.mongooseModels);
updateTagsSpec(options.tags || options.mongooseModels);
if (isEnvironmentIgnored) {
return;
}
responseMiddlewareHasBeenApplied = true;
/** middleware to handle RESPONSES */
app.use((req, res, next) => {
try {
const methodAndPathKey = getMethod(req);
if (methodAndPathKey && methodAndPathKey.method) {
processors.processResponse(res, methodAndPathKey.method, () => {
writeSpecToOutputFile();
});
}
} catch (e) {
/** TODO - shouldn't we do something here? */
} finally {
/** always call the next middleware */
next();
}
});
}
/**
* @type { typeof import('./index').handleRequests }
*/
function handleRequests() {
const isIgnoredEnvironment = ignoredNodeEnvironments.includes(process.env.NODE_ENV);
if (serveDocs || !isIgnoredEnvironment) {
/** forward options to `serveApiDocs`: */
serveApiDocs();
}
if (isIgnoredEnvironment) {
return;
}
/** make sure the middleware placement order (by the user) is correct */
if (responseMiddlewareHasBeenApplied !== true) {
throw new Error(WRONG_MIDDLEWARE_ORDER_ERROR);
}
/** everything was applied correctly; reset the global variable. */
responseMiddlewareHasBeenApplied = false;
if (specOutputPath) {
ensureDirectoryExistence(specOutputPath);
}
/** 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);
writeSpecToOutputFile();
}
} catch (e) {
/** TODO - shouldn't we do something here? */
} finally {
next();
}
});
}
/**
* TODO
*
* 1. Rename the parameter names
* (this will require better global variable naming to allow re-assigning properly)
*
* 2. the `aPath` is ignored only if it's `undefined`,
* but if it's set to an empty string `''`, then the tests fail.
* I think we should be checking for falsy values, not only `undefined` ones.
*
* 3. (Breaking) Use object for optional parameters:
* https://github.com/mpashkovskiy/express-oas-generator/issues/35
*
*/
/**
* @type { typeof import('./index').init }
*/
function init(aApp, aPredefinedSpec = {}, aSpecOutputPath = undefined, aWriteInterval = 0, aSwaggerUiServePath = DEFAULT_SWAGGER_UI_SERVE_PATH, aMongooseModels = [], aTags = undefined, aIgnoredNodeEnvironments = DEFAULT_IGNORE_NODE_ENVIRONMENTS, aAlwaysServeDocs = undefined, aSpecOutputFileBehavior = SPEC_OUTPUT_FILE_BEHAVIOR.RECREATE, aSwaggerDocumentOptions = {}) {
handleResponses(aApp, {
swaggerUiServePath: aSwaggerUiServePath,
specOutputPath: aSpecOutputPath,
predefinedSpec: aPredefinedSpec,
writeIntervalMs: aWriteInterval,
mongooseModels: aMongooseModels,
tags: aTags,
ignoredNodeEnvironments: aIgnoredNodeEnvironments,
alwaysServeDocs: aAlwaysServeDocs,
specOutputFileBehavior: aSpecOutputFileBehavior,
swaggerDocumentOptions: aSwaggerDocumentOptions
});
setTimeout(() => handleRequests(), 1000);
}
/**
* @type { typeof import('./index').getSpec }
*/
const getSpec = () => {
return patchSpec(predefinedSpec);
};
/**
* @type { typeof import('./index').getSpecV3 }
*/
const getSpecV3 = callback => {
convertOpenApiVersionToV3(getSpec(), callback);
};
/**
* @type { typeof import('./index').setPackageInfoPath }
*
* @param pkgInfoPath path to package.json
*/
const setPackageInfoPath = pkgInfoPath => {
packageJsonPath = `${process.cwd()}/${pkgInfoPath}/package.json`;
};
module.exports = {
handleResponses,
handleRequests,
init,
getSpec,
getSpecV3,
setPackageInfoPath,
SPEC_OUTPUT_FILE_BEHAVIOR
};