-
Notifications
You must be signed in to change notification settings - Fork 488
/
Copy pathswagger-module.ts
81 lines (73 loc) · 2.09 KB
/
swagger-module.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
import { INestApplication } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import {
SwaggerBaseConfig,
SwaggerCustomOptions,
SwaggerDocument,
SwaggerDocumentOptions
} from './interfaces';
import { SwaggerScanner } from './swagger-scanner';
export class SwaggerModule {
private static readonly swaggerScanner = new SwaggerScanner();
public static createDocument(
app: INestApplication,
config: SwaggerBaseConfig,
options: SwaggerDocumentOptions = {}
): SwaggerDocument {
const document = this.swaggerScanner.scanApplication(
app,
options.include || []
);
return {
...config,
...document,
swagger: '2.0'
};
}
public static setup(
path: string,
app: INestApplication,
document: SwaggerDocument,
options?: SwaggerCustomOptions
) {
const httpAdapter = app.getHttpAdapter();
if (
httpAdapter &&
httpAdapter.constructor &&
httpAdapter.constructor.name === 'FastifyAdapter'
) {
return this.setupFastify(path, httpAdapter, document);
}
return this.setupExpress(path, app, document, options);
}
private static setupExpress(
path: string,
app: INestApplication,
document: SwaggerDocument,
options?: SwaggerCustomOptions
) {
const validatePath = (path): string =>
path.charAt(0) !== '/' ? '/' + path : path;
const finalPath = validatePath(path);
const swaggerUi = loadPackage('swagger-ui-express', 'SwaggerModule');
const swaggerHtml = swaggerUi.generateHTML(document, options);
app.use(finalPath, swaggerUi.serveFiles(document, options));
app.use(finalPath, (req, res) => res.send(swaggerHtml));
app.use(finalPath + '-json', (req, res) => res.json(document));
}
private static setupFastify(
path: string,
httpServer: any,
document: SwaggerDocument
) {
httpServer.register(loadPackage('fastify-swagger', 'SwaggerModule'), {
swagger: document,
exposeRoute: true,
routePrefix: path,
mode: 'static',
specification: {
document
}
});
}
}