-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathswagger.ts
156 lines (142 loc) · 5.51 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
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of the swagger-service.
*
* @module internal/swagger
*/
import { promises as fs } from 'fs';
import * as path from 'path';
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import Validator, { SwaggerSpecification } from 'swagger-model-validator';
import expressJSDocSwagger from 'express-jsdoc-swagger';
import log4js, { Logger } from 'log4js';
export default class Swagger {
private static logger: Logger = log4js.getLogger('SwaggerGenerator');
/**
* Generate Swagger specification on-demand and serve it.
* @param app - The express application to mount on.
* @param filesPattern - Glob pattern to find your jsdoc files
* @returns The Swagger specification with model validator.
*/
public static generateSpecification(app: express.Application, filesPattern: string[]): Promise<SwaggerSpecification> {
return new Promise((resolve, reject) => {
const options = {
info: {
version: process.env.npm_package_version ? process.env.npm_package_version : 'v1.0.0',
title: process.env.npm_package_name ? process.env.npm_package_name : 'SudoSOS',
description: process.env.npm_package_description ? process.env.npm_package_description : 'SudoSOS',
},
'schemes': [
'http',
'https',
],
servers: [
{
url: `http://${process.env.API_HOST}${process.env.API_BASEPATH}`,
description: 'Development server',
},
],
security: {
JWT: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
baseDir: __dirname,
// Glob pattern to find your jsdoc files
filesPattern,
exposeApiDocs: true, // Expose API Docs JSON
apiDocsPath: '/api-docs.json',
};
const instance = expressJSDocSwagger(app)(options);
instance.on('finish', async (swaggerObject) => {
Swagger.logger.trace('Swagger specification generation finished');
new Validator(swaggerObject);
await fs.writeFile(
path.join(process.cwd(), 'out/swagger.json'),
JSON.stringify(swaggerObject),
{ encoding: 'utf-8' },
).catch((e) => {
console.error(e);
});
instance.removeAllListeners();
resolve(swaggerObject); // Resolve the promise with the swaggerObject
});
instance.on('error', (error) => {
Swagger.logger.error('Error generating Swagger specification:', error);
instance.removeAllListeners();
reject(error); // Reject the promise in case of an error
});
});
}
/**
* Imports a pre-generated Swagger specification file.
* @param file - The path to the Swagger JSON file.
*/
public static async importSpecification(file = 'out/swagger.json'): Promise<SwaggerSpecification> {
const contents = await fs.readFile(file, 'utf-8');
const swaggerSpec = JSON.parse(contents);
new Validator(swaggerSpec);
return swaggerSpec;
}
/**
* Initializes the Swagger specification for the current environment and serve it.
* Depending on the NODE_ENV, it will be generated on-demand or import a pre-generated
* specification.
* @param app - The express application which will serve the specification.
*/
public static async initialize(app: express.Application): Promise<SwaggerSpecification> {
if (process.env.NODE_ENV === 'production') {
// Serve pre-generated Swagger specification in production environments.
const specification = await Swagger.importSpecification();
specification.info = {
version: process.env.npm_package_version ? process.env.npm_package_version : 'v1.0.0',
title: process.env.npm_package_name ? process.env.npm_package_name : 'SudoSOS',
description: process.env.npm_package_description ? process.env.npm_package_description : 'SudoSOS',
};
specification.servers = [
{
url: `https://${process.env.API_HOST}${process.env.API_BASEPATH}`,
description: 'Production server',
},
];
app.use('/api-docs.json', (_, res) => res.json(specification));
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specification));
return specification;
}
return Swagger.generateSpecification(app, [
'../controller/*.ts',
'../helpers/pagination.ts',
'../controller/request/*.ts',
'../controller/response/*.ts',
'../controller/response/**/*.ts',
'../gewis/controller/**/*.ts',
]);
}
}
if (require.main === module) {
// Only execute directly if this is the main execution file.
const app = express();
void fs.mkdir('out', { recursive: true })
.then(async () => { await Swagger.initialize(app); });
}