This repository has been archived by the owner on May 2, 2024. It is now read-only.
/
swagger.ts
686 lines (609 loc) · 18.6 KB
/
swagger.ts
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/**
* This file is part of the @egodigital/express-controllers distribution.
* Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
*
* @egodigital/express-controllers is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* @egodigital/express-controllers is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import * as _ from 'lodash';
import * as express from 'express';
import * as swaggerUi from 'swagger-ui-express';
import * as yaml from 'js-yaml';
import { AUTHORIZER_OPTIONS } from './authorize';
import { Controller, DecoratorFunction, REQUEST_VALIDATORS, ExpressApp } from './index';
import { asArray, compareValuesBy, isEmptyString, normalizeString, toBooleanSafe, toStringSafe } from './utils';
import { RequestHandler } from 'express';
/**
* Possible value for an API url scheme.
*/
export type ApiUrlScheme = 'http' | 'https';
/**
* General information of a Swagger document.
*/
export interface InitControllersSwaggerDocumentOptions {
/**
* The base path of the API.
*/
basePath?: string;
/**
* External docs.
*/
externalDocs?: SwaggerExternalDocs;
/**
* The host name.
*/
host?: string;
/**
* Information about the document.
*/
info?: SwaggerDocumentInfo;
/**
* The list of possible schemes.
*/
schemes?: ApiUrlScheme | ApiUrlScheme[];
/**
* Global security definitions.
*/
security?: SwaggerSecurityDefintion[];
/**
* Security definitions.
*/
securityDefinitions?: SwaggerDefinitionList;
/**
* List of tags (key => name; value => description).
*/
tags?: { [name: string]: string };
}
/**
* 'swagger' extension for options of 'initControllers()' function.
*/
export interface InitControllersSwaggerOptions {
/**
* Support download of YAML and JSON files or not. Default: (true)
*/
canDownload?: boolean;
/**
* Custom CSS for the UI.
*/
css?: string;
/**
* The list of definitions.
*/
definitions?: {
[name: string]: any,
};
/**
* General document information.
*/
document?: InitControllersSwaggerDocumentOptions;
/**
* Custom Favicon for the UI.
*/
favIcon?: string;
/**
* The custom root endpoint (name). Default: '/swagger'
*/
root?: string;
/**
* Custom site title.
*/
title?: string;
/**
* Custom (Swagger) URL.
*/
url?: string;
/**
* One or more, optional middlewares to use.
*/
use?: express.RequestHandler | express.RequestHandler[];
}
/**
* A possible value for 'swagger' property of 'InitControllersSwaggerOptions' interface.
*
* (false) indicates NOT to setup Swagger UI.
*/
export type InitControllersSwaggerOptionsValue = InitControllersSwaggerOptions | false;
/**
* List of Swagger definitions.
*/
export type SwaggerDefinitionList = {
[key: string]: any
};
/**
* Information of a Swagger document.
*/
export interface SwaggerDocumentInfo {
/**
* Contact information.
*/
contact?: SwaggerDocumentInfoContact;
/**
* API description.
*/
description?: string;
/**
* License information.
*/
license?: SwaggerDocumentInfoLicense;
/**
* Version.
*/
version?: string;
/**
* The title.
*/
title?: string;
}
/**
* Contact information in the 'info' block of a Swagger document.
*/
export interface SwaggerDocumentInfoContact {
/**
* The email address.
*/
email?: string;
/**
* The display name of the contact.
*/
name?: string;
/**
* The URL.
*/
url?: string;
}
/**
* License information in the 'info' block of a Swagger document.
*/
export interface SwaggerDocumentInfoLicense {
/**
* The display name of the license.
*/
name?: string;
/**
* The URL.
*/
url?: string;
}
/**
* Swagger external documentation information.
*/
export interface SwaggerExternalDocs {
/**
* A description.
*/
description?: string;
/**
* The URL to the documentation.
*/
url?: string;
}
/**
* Information for generating a Swagger document (path definition).
*/
export interface SwaggerInfo {
/**
* The underlying controller.
*/
controller?: Controller<unknown>;
/**
* The underlying controller method.
*/
controllerMethod?: Function;
/**
* The controller's root path.
*/
controllerRootPath?: string;
/**
* List of router methods, grouped by paths.
*/
groupedRouterMethods: {
[path: string]: string[],
};
/**
* List of supported methods.
*/
methods?: string[];
/**
* The middlewares, which are defined for that route.
*/
middlewares?: RequestHandler[];
/**
* Custom options.
*/
options?: SwaggerOptions;
/**
* The path definition.
*/
pathDefinition: SwaggerPathDefinition;
}
/**
* Additional, custom options for 'Swagger()' decorator.
*/
export interface SwaggerOptions {
/**
* A function that updates swagger path definitions.
*/
pathDefinitionUpdater?: SwaggerPathDefinitionUpdater;
}
/**
* A swagger path definition.
*/
export type SwaggerPathDefinition = any;
/**
* Updates a Swagger path definition.
*
* @param {SwaggerPathDefinitionUpdaterContext} context The context.
*/
export type SwaggerPathDefinitionUpdater =
(context: SwaggerPathDefinitionUpdaterContext) => any;
/**
* An execution context for a 'SwaggerPathDefinitionUpdater' function.
*/
export interface SwaggerPathDefinitionUpdaterContext {
/**
* The path definition to update.
*/
definition: SwaggerPathDefinition;
/**
* Indicates if endpoint does validate or not.
*/
doesValidate: boolean;
/**
* Indicates if underlying method is marked with 'Authorize()' decorator or not.
*/
hasAuthorize: boolean;
/**
* The HTTP method.
*/
method: string;
/**
* The middlewares, which are defined for that route.
*/
middlewares: RequestHandler[];
/**
* The route path.
*/
path: string;
}
/**
* A security defintion.
*/
export type SwaggerSecurityDefintion = { [name: string]: any[] };
/**
* Key for storing a SwaggerInfo document.
*/
export const SWAGGER_INFO = Symbol('SWAGGER_INFO');
let swaggerPathDefinitionUpdater: SwaggerPathDefinitionUpdater;
/**
* Defines a Swagger definition for a controller method.
*
* @param {SwaggerPathDefinition} pathDefinition The path definition.
* @param {SwaggerOptions} [opts] Custom and additional options.
*
* @return {DecoratorFunction} The decorator function.
*/
export function Swagger(pathDefinition: SwaggerPathDefinition, opts?: SwaggerOptions): DecoratorFunction;
/**
* Defines a Swagger definition for a controller method.
*
* @param {SwaggerPathDefinition} pathDefinition The path definition.
* @param {SwaggerPathDefinitionUpdater} pathDefinitionUpdater A function that updates path definitions.
*
* @return {DecoratorFunction} The decorator function.
*/
export function Swagger(pathDefinition: SwaggerPathDefinition, pathDefinitionUpdater: SwaggerPathDefinitionUpdater): DecoratorFunction;
/**
* Defines a Swagger definition for a controller method.
*
* @param {SwaggerPathDefinitionUpdater} pathDefinitionUpdater A function that updates path definitions.
* @param {SwaggerPathDefinition} pathDefinition The path definition.
*
* @return {DecoratorFunction} The decorator function.
*/
export function Swagger(pathDefinitionUpdater: SwaggerPathDefinitionUpdater, pathDefinition: SwaggerPathDefinition): DecoratorFunction;
export function Swagger(...args: any[]): DecoratorFunction {
return function (controllerConstructor: any, name: string, descriptor: PropertyDescriptor) {
const VALUE: Function = descriptor.value;
VALUE[SWAGGER_INFO] = toSwaggerInfo(args);
};
}
/**
* Returns the global function, for updating Swagger path definitions.
*
* @return {SwaggerPathDefinitionUpdater} The handler.
*/
export function getSwaggerPathDefinitionUpdater(): SwaggerPathDefinitionUpdater {
return swaggerPathDefinitionUpdater;
}
/**
* Sets the global function, for updating Swagger path definitions.
*
* @param {SwaggerPathDefinitionUpdater|undefined|null} newUpdater The new handler.
*/
export function setSwaggerPathDefinitionUpdater(
newUpdater: SwaggerPathDefinitionUpdater | null | undefined,
): void {
swaggerPathDefinitionUpdater = newUpdater;
}
/**
* Sets up the swagger UI for an app or router.
*
* @param {ExpressApp} app The Express app or router.
* @param {InitControllersSwaggerOptionsValue} optsOrFalse Swagger options.
* @param {SwaggerInfo[]} infos The list of infos.
*/
export function setupSwaggerUI(
app: ExpressApp, optsOrFalse: InitControllersSwaggerOptionsValue,
infos: SwaggerInfo[],
) {
if (false === optsOrFalse) {
return;
}
let opts = optsOrFalse as InitControllersSwaggerOptions;
if (_.isNil(opts)) {
opts = {} as any;
}
if (!infos.length) {
return;
}
// swagger root path
let swaggerRoot = toStringSafe(opts.root);
if ('' === swaggerRoot.trim()) {
swaggerRoot = '/swagger';
}
if (!swaggerRoot.trim().startsWith('/')) {
swaggerRoot = '/' + swaggerRoot;
}
// prepare version 2.0 document
let newSwaggerDoc = {
'swagger': '2.0',
'info': undefined as any,
'host': undefined as any,
'tags': undefined as any,
'schemes': undefined as any,
'paths': (infos.length ?
{} : undefined) as any,
'definitions': undefined as any,
'externalDocs': undefined as any,
'basePath': undefined as any,
'securityDefinitions': undefined as any,
};
if (opts.document) {
// basePath
if (!isEmptyString(opts.document.basePath)) {
newSwaggerDoc.basePath = toStringSafe(opts.document.basePath)
.trim();
}
// host
if (!isEmptyString(opts.document.host)) {
newSwaggerDoc.host = toStringSafe(opts.document.host)
.trim();
}
// schemes
const ALL_SCHEMES = asArray(opts.document.schemes)
.map(x => toStringSafe(x).toLowerCase().trim())
.filter(x => '' !== x)
.sort();
if (ALL_SCHEMES.length) {
newSwaggerDoc.schemes = ALL_SCHEMES;
}
// externalDocs
if (opts.document.externalDocs) {
newSwaggerDoc.externalDocs = opts.document.externalDocs;
}
// info
if (opts.document.info) {
newSwaggerDoc.info = opts.document.info;
}
// securityDefinitions
if (opts.document.securityDefinitions) {
newSwaggerDoc.securityDefinitions = opts.document.securityDefinitions;
}
// tags
if (opts.document.tags) {
newSwaggerDoc.tags = [];
// sort by tag name
Object.keys(opts.document.tags).sort((x, y) => {
return compareValuesBy(x, y, t => {
return normalizeString(t);
});
}).forEach(t => {
const TAG_NAME = t.trim();
const TAG_DESCRIPTION = toStringSafe(opts.document.tags[t])
.trim();
newSwaggerDoc.tags.push({
name: TAG_NAME,
description: TAG_DESCRIPTION,
});
});
}
}
// custom CSS
let css = toStringSafe(opts.css);
if (isEmptyString(css)) {
css = null;
}
// fav icon
let favIcon = toStringSafe(opts.favIcon);
if (isEmptyString(favIcon)) {
favIcon = null;
}
// Swagger URL
let url = toStringSafe(opts.url);
if (isEmptyString(url)) {
url = null;
}
// custom site title
let title = toStringSafe(opts.title);
if (isEmptyString(title)) {
title = null;
}
if (opts.definitions) {
newSwaggerDoc.definitions = {};
// sort by name
Object.keys(opts.definitions).sort((x, y) => {
return compareValuesBy(x, y, dn => {
return normalizeString(dn);
});
}).forEach(dn => {
const DEF_NAME = dn.trim();
if ('' === DEF_NAME) {
return;
}
newSwaggerDoc.definitions[DEF_NAME] = opts.definitions[dn];
});
}
if (newSwaggerDoc.paths) {
// path definitions
const PATH_ACTIONS: {
action: () => void,
swaggerPath: string;
}[] = [];
infos.forEach(si => {
Object.keys(si.groupedRouterMethods).forEach(routePath => {
const SWAGGER_PATH = toSwaggerPath(routePath);
PATH_ACTIONS.push({
swaggerPath: SWAGGER_PATH,
action: () => {
if (_.isNil(newSwaggerDoc.paths[SWAGGER_PATH])) {
newSwaggerDoc.paths[SWAGGER_PATH] = {};
}
// set for each method
si.groupedRouterMethods[routePath].sort().forEach(m => {
let pathDefinition = si.pathDefinition;
let pathDefinitionUpdater: SwaggerPathDefinitionUpdater;
if (si.options) {
pathDefinitionUpdater = si.options.pathDefinitionUpdater;
}
if (_.isNil(pathDefinitionUpdater)) {
pathDefinitionUpdater = si.controller.__updateSwaggerPath; // controller-wide
}
if (_.isNil(pathDefinitionUpdater)) {
pathDefinitionUpdater = getSwaggerPathDefinitionUpdater(); // global
}
if (pathDefinitionUpdater) {
const UPDATER_CTX: SwaggerPathDefinitionUpdaterContext = {
definition: pathDefinition,
doesValidate: !!asArray(si.controllerMethod[REQUEST_VALIDATORS]).length,
hasAuthorize: !_.isNil(si.controllerMethod[AUTHORIZER_OPTIONS]),
method: m.toUpperCase(),
middlewares: asArray(si.middlewares),
path: routePath,
};
pathDefinitionUpdater(
UPDATER_CTX
);
pathDefinition = UPDATER_CTX.definition;
}
if (pathDefinition) {
newSwaggerDoc.paths[SWAGGER_PATH][m] = pathDefinition;
}
});
},
});
});
});
// sort by Swagger path
PATH_ACTIONS.sort((x, y) => {
return compareValuesBy(x, y, i => {
return normalizeString(i.swaggerPath);
});
}).forEach(pa => {
pa.action();
});
}
const ROUTER = express.Router();
// setup UI
{
const MIDDLEWARES = asArray(opts.use);
if (MIDDLEWARES.length) {
// additional middlewares
ROUTER.use.apply(
ROUTER, MIDDLEWARES
);
}
ROUTER.use('/', swaggerUi.serveFiles(newSwaggerDoc));
ROUTER.get('/', swaggerUi.setup(
newSwaggerDoc,
null, // opts
null, // options
css, // customCss
favIcon, // customfavIcon
url, // swaggerUrl
title, // customeSiteTitle
));
}
// we need a clean object here
newSwaggerDoc = JSON.parse(
JSON.stringify(newSwaggerDoc)
);
if (toBooleanSafe(opts.canDownload, true)) {
// download link (JSON)
const JSON_DOC = JSON.stringify(newSwaggerDoc, null, 2);
ROUTER.get(`/json`, function (req, res) {
return res.status(200)
.header('content-type', 'application/json; charset=utf-8')
.header('content-disposition', `attachment; filename=api.json`)
.send(
Buffer.from(JSON_DOC, 'utf8')
);
});
// download link (YAML)
const YAML_DOC = yaml.dump(newSwaggerDoc);
ROUTER.get(`/yaml`, function (req, res) {
return res.status(200)
.header('content-type', 'application/x-yaml; charset=utf-8')
.header('content-disposition', `attachment; filename=api.yaml`)
.send(
Buffer.from(YAML_DOC, 'utf8')
);
});
}
app.use(swaggerRoot, ROUTER);
}
function toSwaggerInfo(args: any[]): SwaggerInfo {
const INFO: SwaggerInfo = {
groupedRouterMethods: {},
pathDefinition: undefined,
};
const FIRST_ARG: any = args[0];
if (_.isFunction(FIRST_ARG)) {
// [0] pathDefinitionUpdater: SwaggerPathDefinitionUpdater
// [1] pathDefinition: SwaggerPathDefinition
INFO.pathDefinition = args[1] as SwaggerPathDefinition;
INFO.options = {
pathDefinitionUpdater: FIRST_ARG as SwaggerPathDefinitionUpdater,
};
} else {
// [0] pathDefinition: SwaggerPathDefinition
INFO.pathDefinition = FIRST_ARG as SwaggerPathDefinition;
if (args.length > 1) {
if (_.isFunction(args[1])) {
// [1] pathDefinitionUpdater: SwaggerPathDefinitionUpdater
INFO.options = {
pathDefinitionUpdater: args[1] as SwaggerPathDefinitionUpdater,
};
} else {
// [1] opts?: SwaggerOptions
INFO.options = args[1] as SwaggerOptions;
}
}
}
return INFO;
}
function toSwaggerPath(p: string) {
p = p.replace(
/(\:)([^\/|^\(|^\)]+)([\/|\(|\)]?)/ig,
'{$2}$3'
);
return p;
}