-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
466 lines (438 loc) · 13.8 KB
/
index.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
import { swaggerize, common, initialise, compile, json, ensureValid } from 'swagger-spec-express';
import j2s from 'joi-to-swagger';
import responsesEnum from './responsesEnum';
import { isEmpty, map, get, has } from 'lodash';
import fs from 'fs';
import { resolve, join } from 'path';
import convert from 'koa-convert';
import mount from 'koa-mount';
import swaggerUi from 'swagger-ui-koa';
import Validation from './validation/validate';
/**
* This module will support all the functionality of swagger-spec-express with additonal
* functions of this module.
* This module uses swagger-spec-express, swagger-ui-express and joi-to-swagger modules to
* generate swagger documentation with joi validation.
*/
export = {
swaggerize,
createModel,
serveSwagger,
describeSwaggerWithoutPath,
validation: Validation
};
/**
* This will create models for all the provides responses(with joi vlaidations).
* @param {object} responseModel
*/
function createResponseModel({ responseModel, name }: { responseModel: any; name: string }) {
let isArray = false;
if (responseModel && Array.isArray(responseModel) && responseModel.length) {
isArray = true;
responseModel = responseModel[0];
}
for (const property in responseModel) {
if (typeof responseModel[property] === 'string') {
responseModel[property] = {
type: responseModel[property],
};
}
}
const bodyParameter: any = {
type: isArray ? 'array' : 'object',
};
if (isArray) {
bodyParameter.items = {
type: 'object',
properties: responseModel,
};
} else {
bodyParameter.properties = responseModel;
}
const model = Object.assign(
{
name,
},
bodyParameter,
);
common.addModel(model);
}
/**
* Serve swagger.
* @param {*} app express object.
* @param {*} endPoint swagger end point.
* @param {*} options swagger options.
*/
function serveSwagger(
app: any,
endPoint: string,
options: object,
path: { routePath?: string; requestModelPath: string; responseModelPath: string },
) {
if (path.routePath) {
describeSwagger(app, path.routePath, path.requestModelPath, path.responseModelPath);
} else {
describeSwaggerWithoutPath(app, path.requestModelPath, path.responseModelPath);
}
initialise(app, options);
compile(); // compile swagger document
app.use(swaggerUi.serve); // serve swagger static files
app.use(convert(mount(endPoint, swaggerUi.setup(json(), false, null, null, null))));
}
/**
* This function will generate json for the success response.
* @param {object} schema
* @param {object} describe
*/
function createResponses(schema: any, responseModel: any, describe: any) {
const responses: any = {
500: {
description: responsesEnum[500],
},
};
try {
if (responseModel && !isEmpty(responseModel)) {
for (const key in responseModel) {
if (responseModel.hasOwnProperty(key)) {
createResponseModel({
responseModel: responseModel[key],
name: `${schema.model}${key}ResponseModel`,
});
responses[key] = {
description: responsesEnum[key] ? responsesEnum[key] : '',
schema: {
$ref: `#/definitions/${schema.model}${key}ResponseModel`,
},
};
}
}
}
describe.responses = responses;
return describe;
} catch (error) {
console.log('responseModel', responseModel);
console.log('Error while generting response model for swagger', error);
describe.responses = responses;
return describe;
}
}
/**
* This function will generate json given header parameter in schema(with joi validation).
* @param {object} schema
* @param {object} describe
*/
function getHeader(schema: any, describe: any) {
const arr = [];
for (const key in schema) {
if (schema.hasOwnProperty(key)) {
arr.push(key);
const query = schema[key];
const queryObject = {
name: key,
type: query.type ? query.type : query,
required: query.required === 'undefined' ? false : true,
};
if (query._flags && query._flags.presence) {
queryObject.required = query._flags.presence === 'required' ? true : false;
}
common.parameters.addHeader(queryObject);
}
}
if (describe.common.parameters) {
describe.common.parameters.header = arr;
} else {
describe.common.parameters = {};
describe.common.parameters.header = arr;
}
return describe;
}
/**
* This function will create models for given path and query schema and
* convert it to json(with joi validation).
* @param {object} schema
* @param {string} value either query and path
* @param {object} describe
*/
function getQueryAndPathParamObj(schema: any, value: string, describe: any) {
const arr = [];
for (const key in schema) {
if (schema.hasOwnProperty(key)) {
arr.push(key);
const query = schema[key];
const queryObject = {
name: key,
type: query.type ? query.type : query,
required: query.required === 'undefined' ? false : true,
};
if (query._flags && query._flags.presence) {
queryObject.required = query._flags.presence === 'required' ? true : false;
}
value === 'query' ? common.parameters.addQuery(queryObject) : common.parameters.addPath(queryObject);
}
}
if (describe.common.parameters) {
value === 'query' ? (describe.common.parameters.query = arr) : (describe.common.parameters.path = arr);
} else {
describe.common.parameters = {};
value === 'query' ? (describe.common.parameters.query = arr) : (describe.common.parameters.path = arr);
}
return describe;
}
/**
* This function will create models for given body schema
* and convert it to json(with joi validation).
* @param {object} schema
* @param {object} describe
*/
function getBodyParameters(
schema: { body: any; model: any; description: any },
describe: { tags?: any[]; common: any },
) {
const bodyParameter = j2s(schema.body).swagger;
const model = Object.assign(
{
name: `${schema.model}Model`,
},
bodyParameter,
);
common.addModel(model);
common.parameters.addBody({
name: `${schema.model}Model`,
required: true,
description: schema.description || undefined,
schema: {
$ref: `#/definitions/${schema.model}Model`,
},
});
describe.common = {
parameters: {
body: [`${schema.model}Model`],
},
};
return describe;
}
/**
* This function will create proper schema based on given body, query, header and path parameter
* mentioned in the schema.
* @param {object} schema this is schema mentioned for each API in a route.
*/
function createModel(schema: any, responseModel: { [x: string]: any; hasOwnProperty: (arg0: string) => void }) {
let describe: any = {
tags: [schema.group],
common: {},
};
describe = {
...createResponses(schema, responseModel, describe),
};
if (schema && schema.body) {
const bodyParams = getBodyParameters(schema, describe);
describe = {
...bodyParams,
};
}
if (schema && schema.query) {
const queryParams = getQueryAndPathParamObj(schema.query, 'query', describe);
describe = {
...queryParams,
};
}
if (schema && schema.path) {
const pathParams = getQueryAndPathParamObj(schema.path, 'path', describe);
describe = {
...pathParams,
};
}
if (schema && schema.header) {
const headerParams = getHeader(schema.header, describe);
describe = {
...headerParams,
};
}
return describe;
}
/**
* @param app : Koa object
* @param routePath : routh folder path.
* @param requestModelPath : request model path
* @param responseModelPath : responsemodel model path.
*/
function describeSwagger(app: any, routePath: string, requestModelPath: string, responseModelPath: any) {
try {
app._router = {
stack: [],
};
const rootPath = resolve(__dirname).split('node_modules')[0];
fs.readdirSync(join(rootPath, routePath)).forEach((file: any) => {
if (!file) {
console.log('No router file found in given folder');
return;
}
let responseModel;
let requestModel;
const route = join(rootPath, routePath, file);
const router = require(route);
if (!router || !router.stack) {
console.log('Router missing');
return;
}
if (responseModelPath) {
const responseModelFullPath = join(rootPath, responseModelPath, file);
if (fs.existsSync(responseModelFullPath)) {
responseModel = require(responseModelFullPath);
} else {
console.log('Response model path does not exist responseModelFullPath->', responseModelFullPath);
}
}
if (requestModelPath) {
const requestModelFullPath = join(rootPath, requestModelPath, file);
if (fs.existsSync(requestModelFullPath)) {
requestModel = require(requestModelFullPath);
} else {
console.log('Response model path does not exist requestModelFullPath->', requestModelFullPath);
}
}
processRouter(app, router, requestModel, responseModel, file.split('.')[0]);
});
} catch (error) {
console.log(`Error in describeSwagger ${error}`);
return;
}
}
function processRouter(app: any, item: any, requestModel: any, responseModel: any, routerName: any) {
try {
if (item.stack && item.stack.length > 0) {
let count = 0;
// tslint:disable-next-line:no-unused-expression
map(item.stack, (route: any) => {
let routeRequestModel = get(requestModel, [count]);
const routeResposeModel = get(responseModel, get(routeRequestModel, ['model']));
if (routeRequestModel && routeRequestModel.excludeFromSwagger) {
count++;
return;
}
if (!routeRequestModel || !has(routeRequestModel, 'group')) {
routeRequestModel = {
group: routerName,
description: routerName,
};
}
const data = Object.assign({}, createModel(routeRequestModel, routeResposeModel));
describeRouterRoute(route, data);
app._router['stack'].push(route);
count++;
return item;
})[0];
}
} catch (error) {
console.log(`Error in processRouter ${error}`);
return;
}
}
function describeRouterRoute(router: any, metaData: any) {
if (metaData.described) {
console.warn('Route already described');
return;
}
if (!metaData) {
throw new Error('Metadata must be set when calling describe');
}
if (!router) {
throw new Error(
// tslint:disable-next-line:max-line-length
'router was null, either the item that swaggerize & describe was called on is not an express app/router or you have called describe before adding at least one route',
);
}
if (!router) {
throw new Error(
// tslint:disable-next-line:max-line-length
'Unable to add swagger metadata to last route since the last item in the stack was not a route. Route name :' +
router.name +
'. Metadata :' +
JSON.stringify(metaData),
);
}
const verb = router.methods[0] === 'HEAD' ? router.methods[1] : router.methods[0];
if (!verb) {
throw new Error(
// tslint:disable-next-line:max-line-length
"Unable to add swagger metadata to last route since the last route's methods property was empty" +
router.name +
'. Metadata :' +
JSON.stringify(metaData),
);
}
ensureValid(metaData);
ensureAtLeastOneResponse(metaData);
metaData.path = router.path;
metaData.verb = verb.toLowerCase();
router.swaggerData = metaData;
router.route = {
swaggerData: metaData,
path: metaData.path,
};
metaData.described = true;
}
/**
* @param app : Koa object
* @param requestModelPath : request model path
* @param responseModelPath : responsemodel model path.
*/
function describeSwaggerWithoutPath(app: any, requestModelPath: string, responseModelPath: string) {
try {
app._router = {
stack: [],
};
const rootPath = resolve(__dirname).split('node_modules')[0];
app.middleware.forEach((middleware: any) => {
let responseModel;
let requestModel;
if (middleware.name !== 'dispatch') {
return;
}
if (!middleware.router || !middleware.router.stack) {
console.log('Router missing');
return;
}
const routerPrefix = get(middleware, ['router', 'opts', 'prefix']);
let routerBasePath;
if (routerPrefix) {
routerBasePath = routerPrefix.replace(/\//g, '');
}
if (!routerBasePath) {
routerBasePath = 'Home';
}
if (responseModelPath && routerPrefix) {
const responseModelFullPath = join(rootPath, responseModelPath, `${routerPrefix}.js`);
if (fs.existsSync(responseModelFullPath)) {
responseModel = require(responseModelFullPath);
} else {
console.log('Response model path does not exist responseModelFullPath->', responseModelFullPath);
}
}
if (requestModelPath && routerPrefix) {
const requestModelFullPath = join(rootPath, requestModelPath, `${routerPrefix}.js`);
if (fs.existsSync(requestModelFullPath)) {
requestModel = require(requestModelFullPath);
} else {
console.log('Response model path does not exist requestModelFullPath->', requestModelFullPath);
}
}
processRouter(app, middleware.router, requestModel, responseModel, routerBasePath);
});
} catch (error) {
console.log(`Error in describeSwagger ${error}`);
return;
}
}
function ensureAtLeastOneResponse(metaData: any) {
if (metaData.responses && Object.keys(metaData.responses).length > 0) {
return;
}
if (metaData.common && metaData.common.responses.length > 0) {
return;
}
throw new Error(
// tslint:disable-next-line:max-line-length
'Each metadata description for a route must have at least one response, either specified in metaData.responses or metaData.common.responses.',
);
}