forked from zone-eu/restify-api-generate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restifyOpenapiGenerator.js
399 lines (327 loc) · 13.9 KB
/
restifyOpenapiGenerator.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
'use strict';
const fs = require('fs');
const structuredCloneWrapper = typeof structuredClone === 'function' ? structuredClone : obj => JSON.parse(JSON.stringify(obj));
// ignore function and symbol types
const joiTypeToOpenApiTypeMap = {
any: 'object',
number: 'number',
link: 'string',
boolean: 'boolean',
date: 'string',
string: 'string',
binary: 'string'
};
class RestifyApiGenerate {
constructor(joi, dirname) {
this.Joi = joi;
this.dirname = dirname;
if (!dirname) {
throw Error('Pass in your __dirname as the second parameter');
}
}
replaceWithRefs(reqBodyData) {
if (reqBodyData.type === 'array') {
const obj = reqBodyData.items;
this.replaceWithRefs(obj);
} else if (reqBodyData.type === 'object') {
if (reqBodyData.objectName) {
const objectName = reqBodyData.objectName;
Object.keys(reqBodyData).forEach(key => {
if (key !== '$ref' || key !== 'description') {
delete reqBodyData[key];
}
});
reqBodyData.$ref = `#/components/schemas/${objectName}`;
} else {
for (const key in reqBodyData.properties) {
this.replaceWithRefs(reqBodyData.properties[key]);
}
}
} else if (reqBodyData.type === 'alternatives') {
for (const obj in reqBodyData.oneOf) {
this.replaceWithRefs(obj);
}
}
}
parseComponetsDecoupled(component, components) {
if (component.type === 'array') {
const obj = structuredCloneWrapper(component.items); // copy
if (obj.objectName) {
for (const key in obj.properties) {
this.parseComponetsDecoupled(obj.properties[key], components);
}
// in case the Array itself is marked as a separate object >
const objectName = obj.objectName;
components[objectName] = obj;
delete components[objectName].objectName;
// ^
}
} else if (component.type === 'object') {
const obj = structuredCloneWrapper(component); // copy
const objectName = obj.objectName;
for (const key in obj.properties) {
this.parseComponetsDecoupled(obj.properties[key], components);
}
if (objectName) {
components[objectName] = obj;
delete components[objectName].objectName;
}
} else if (component.oneOf) {
// Joi object is of 'alternatives' types
for (const obj in component.oneOf) {
this.parseComponetsDecoupled({ ...obj }, components);
}
}
}
/**
* Parse Joi Objects
*/
parseJoiObject(path, joiObject, requestBodyProperties) {
if (joiObject.type === 'object') {
const fieldsMap = joiObject._ids._byKey;
const data = {
type: joiObject.type,
description: joiObject._flags.description,
properties: {},
required: []
};
if (joiObject._flags.objectName) {
data.objectName = joiObject._flags.objectName;
}
if (path) {
requestBodyProperties[path] = data;
} else if (Array.isArray(requestBodyProperties)) {
requestBodyProperties.push(data);
} else {
requestBodyProperties.items = data;
}
for (const [key, value] of fieldsMap) {
if (value.schema._flags.presence === 'required') {
data.required.push(key);
}
this.parseJoiObject(key, value.schema, data.properties);
}
} else if (joiObject.type === 'alternatives') {
const matches = joiObject.$_terms.matches;
const data = {
oneOf: [],
description: joiObject._flags.description
};
if (path) {
requestBodyProperties[path] = data;
} else if (Array.isArray(requestBodyProperties)) {
requestBodyProperties.push(data);
} else {
requestBodyProperties.items = data;
}
for (const alternative of matches) {
this.parseJoiObject(null, alternative.schema, data.oneOf);
}
} else if (joiObject.type === 'array') {
const elems = joiObject?.$_terms.items;
const data = {
type: 'array',
items: {},
description: joiObject._flags.description
};
if (path) {
requestBodyProperties[path] = data;
} else if (Array.isArray(requestBodyProperties)) {
requestBodyProperties.push(data);
} else {
requestBodyProperties.items = data;
}
this.parseJoiObject(null, elems[0], data);
} else {
const openApiType = joiTypeToOpenApiTypeMap[joiObject.type]; // even if type is object here then ignore and do not go recursive
const isRequired = joiObject._flags.presence === 'required';
const description = joiObject._flags.description;
let format = undefined;
if (!openApiType) {
throw new Error('Unsupported type! Check API endpoint!');
}
if (joiObject.type !== openApiType) {
// type has changed, so probably string, acquire format
format = joiObject.type;
}
const data = { type: openApiType, description, required: isRequired };
if (format) {
data.format = format;
if (data.format === 'date') {
data.format = 'date-time';
}
}
// enum check
if (joiObject._valids) {
const enumValues = [];
for (const validEnumValue of joiObject._valids._values) {
enumValues.push(validEnumValue);
}
if (enumValues.length > 0) {
data.enum = enumValues;
}
}
// example check
if (joiObject.$_terms && joiObject.$_terms.examples && joiObject.$_terms.examples.length > 0) {
const example = joiObject.$_terms.examples[0];
data.example = example;
}
if (path) {
requestBodyProperties[path] = data;
} else if (Array.isArray(requestBodyProperties)) {
requestBodyProperties.push(data);
} else {
requestBodyProperties.items = data;
}
}
}
async generateAPiDocs(routes, options) {
let docs = {
openapi: options.openapiVersion || '3.0.0',
info: options.info || {
title: 'Example API',
description: 'Example API docs',
version: '1.0.0',
contact: {
url: 'https://github.com/example/example'
}
},
servers: options.servers || [{ url: 'https://example.com' }],
tags: options.tags || [
{
name: 'Example tag',
description: 'This is an example tag provided if you do not specify any tags yourself in the options'
}
]
};
const mapPathToMethods = {}; // map -> {path -> {post -> {}, put -> {}, delete -> {}, get -> {}}}
for (const routePath in routes) {
const route = routes[routePath];
const { spec } = route;
if (spec.excludeRoute) {
continue;
}
if (!mapPathToMethods[spec.path]) {
mapPathToMethods[spec.path] = {};
}
mapPathToMethods[spec.path][spec.method.toLowerCase()] = {};
const operationObj = mapPathToMethods[spec.path][spec.method.toLowerCase()];
// 1) add tags
operationObj.tags = spec.tags;
// 2) add summary
operationObj.summary = spec.summary;
// 3) add description
operationObj.description = spec.description;
// 4) add operationId
operationObj.operationId = spec.name || route.name;
// 5) add requestBody
const applicationType = spec.applicationType || 'application/json';
if (spec.validationObjs?.requestBody && Object.keys(spec.validationObjs.requestBody).length > 0) {
operationObj.requestBody = {
content: {
[applicationType]: {
schema: {}
}
},
required: true
};
// convert to Joi object for easier parsing
this.parseJoiObject('schema', this.Joi.object(spec.validationObjs?.requestBody), operationObj.requestBody.content[applicationType]);
}
// 6) add parameters (queryParams and pathParams).
operationObj.parameters = [];
for (const paramKey in spec.validationObjs?.pathParams) {
const paramKeyData = spec.validationObjs.pathParams[paramKey];
const obj = {};
obj.name = paramKey;
obj.in = 'path';
obj.description = paramKeyData._flags.description;
obj.required = paramKeyData._flags.presence === 'required';
obj.schema = { type: paramKeyData.type };
operationObj.parameters.push(obj);
}
for (const paramKey in spec.validationObjs?.queryParams) {
const paramKeyData = spec.validationObjs.queryParams[paramKey];
const obj = {};
obj.name = paramKey;
obj.in = 'query';
obj.description = paramKeyData._flags.description;
obj.required = paramKeyData._flags.presence === 'required';
obj.schema = { type: paramKeyData.type };
// enum check
if (paramKeyData._valids) {
const enumValues = [];
for (const validEnumValue of paramKeyData._valids._values) {
enumValues.push(validEnumValue);
}
if (enumValues.length > 0) {
obj.schema.enum = enumValues;
}
}
// example check
if (paramKeyData.$_terms && paramKeyData.$_terms.examples && paramKeyData.$_terms.examples.length > 0) {
const example = paramKeyData.$_terms.examples[0];
obj.schema.example = example;
}
operationObj.parameters.push(obj);
}
// 7) add responses
const responseType = spec.responseType || 'application/json';
operationObj.responses = {};
for (const resHttpCode in spec.validationObjs?.response) {
const resBodyData = spec.validationObjs.response[resHttpCode];
operationObj.responses[resHttpCode] = {
description: resBodyData.description,
content: {
[responseType]: {
schema: {}
}
}
};
const obj = operationObj.responses[resHttpCode];
this.parseJoiObject('schema', resBodyData.model, obj.content[responseType]);
}
}
const components = { components: { schemas: {} } };
for (const path in mapPathToMethods) {
// for every path
const pathData = mapPathToMethods[path];
for (const httpMethod in pathData) {
// for every http method (post, put, get, delete)
const innerData = pathData[httpMethod];
// for every requestBody obj
for (const key in innerData?.requestBody?.content[Object.keys(innerData.requestBody.content)[0]].schema.properties) {
const reqBodyData = innerData.requestBody.content[Object.keys(innerData.requestBody.content)[0]].schema.properties[key];
this.parseComponetsDecoupled(reqBodyData, components.components.schemas);
this.replaceWithRefs(reqBodyData);
}
// for every response object
for (const key in innerData.responses) {
// key here is http method (2xx, 4xx, 5xx)
const obj = innerData.responses[key].content[Object.keys(innerData.responses[key].content)[0]].schema;
this.parseComponetsDecoupled(obj, components.components.schemas);
this.replaceWithRefs(obj);
}
}
}
// refify components that use other components
for (const obj of Object.values(components.components.schemas)) {
this.replaceWithRefs(obj);
}
const finalObj = { paths: mapPathToMethods };
components.components.securitySchemes = options.components.securitySchemes;
docs = { ...docs, ...finalObj };
docs = { ...docs, ...components };
docs = {
...docs,
security: options.security
};
await fs.promises.writeFile(this.dirname + options.docsPath || '/openapidocs.json', JSON.stringify(docs));
}
restifyApiGenerate(ctx, options) {
const routes = ctx.router.getRoutes();
this.generateAPiDocs(routes, options);
return (req, res, next) => next();
}
}
module.exports = { RestifyApiGenerate };