-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
466 lines (411 loc) · 14.4 KB
/
index.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
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
let swaggerConfig = require('./swagger');
var fs = require('fs');
module.exports = function swaggerGenerator(sails) {
return {
initialize: async function () {
var eventsToWaitFor = [];
if (sails.hooks.orm) {
eventsToWaitFor.push("hook:orm:loaded");
}
if (sails.hooks.pubsub) {
eventsToWaitFor.push("hook:pubsub:loaded");
}
sails.after(eventsToWaitFor, () => {
init();
this.registerActions();
});
},
registerActions: function() {
// Register an action as `myhook/greet` that an app can bind to any route they like.
var html = fs.readFileSync(__dirname + '/index.html', 'utf-8');
sails.registerAction(function greet(req, res) {
return res.status(200).send(html);
}, 'swagger');
sails.config.routes['GET /swagger'] = { action: 'swagger' };
sails.registerAction(function swaggerjson(req, res) {
let jsonFullPath = sails.config.appPath + '/' + swaggerConfig.pathToGenerateFile + swaggerConfig.fileName;
var json = fs.readFileSync(jsonFullPath, 'utf-8');
// console.log("jsonFullPath : ", jsonFullPath);
// console.log("json : ", json);
return res.status(200).send(json);
}, 'swaggerjson');
sails.config.routes['GET /swagger.json'] = { action: 'swaggerjson' };
// return cb();
}
};
function init() {
// getting global object if defined
// console.log('defined In config: ', sails.config.swaggerConfig);
if (sails.config.swaggerConfig) {
_.merge(swaggerConfig, sails.config.swaggerConfig);
}
// console.log('final swagger config: ', swaggerConfig);
// return;
if (swaggerConfig.disable) {
sails.log.info('Swagger hook disabled, please enable it from sails.config.swaggerConfig.disable')
return;
}
sails.log.info(" 🍺 Logistic Infotech's sails-hook-actions2-swagger loaded 🍺 ");
let swagger = swaggerConfig.swagger;
let routeList = sails.config.routes;
let controllerPath = sails.config.paths.controllers;
// console.log('routeList : ', routeList);
for (const key in routeList) {
if (routeList.hasOwnProperty(key)) {
let arrRouteSplit = key.split(/ (.+)/);
let methodType = arrRouteSplit[0].toLowerCase();
let routeUrl = arrRouteSplit[1];
if(arrRouteSplit.length == 1) {
methodType = "get";
routeUrl = arrRouteSplit[0]
}
// console.log('routeList[key] : ', routeList[key]);
// console.log('methodType : ' + methodType + ' routeUrl : ' + routeUrl);
// if route has path params
let pathInputs = [];
let objUrl = {};
if (routeUrl && routeUrl.indexOf(':') > -1) {
objUrl = addCurlyToRoute(routeUrl);
routeUrl = objUrl.routeUrl;
pathInputs = objUrl.pathInputs;
}
let tempTag = routeUrl;
// console.log('view tempTag 1 : ', tempTag);
if (swaggerConfig.defaults.pathsToIgnore.length) {
if (swaggerConfig.defaults.pathsToIgnore.indexOf(tempTag)) {
for (let i = 0; i < swaggerConfig.defaults.pathsToIgnore.length; i++) {
tempTag = tempTag.replace(swaggerConfig.defaults.pathsToIgnore[i], '');
// console.log(' =========>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GONE');
}
}
}
tempTag = tempTag.replace(/\/\/+/g, '/');
// console.log('view tempTag 2 : ', tempTag);
let tags = tempTag.split("/");
// console.log(tags);
// TODO:
let tag = capitalizeString(tags[1]);
if (!tag) {
tag = "/";
}
let summary = routeList[key].description ? routeList[key].description : '';
if(!swagger.paths[routeUrl]) {
swagger.paths[routeUrl] = {};
}
if (routeList[key].controller && routeList[key].swagger) {
// console.log(routeList[key].swagger, routeUrl, methodType);
swagger.paths[routeUrl][methodType] = routeList[key].swagger;
} else if (routeList[key].view) {
objUrl.methodType = methodType;
objUrl.actionInputs = [];
objUrl.tags = [tag];
objUrl.summary = summary;
objUrl.consumes = ["application/json"];
objUrl.produces = ["application/json"];
objUrl.responses = swaggerConfig.defaults.responses;
objUrl.security = swaggerConfig.defaults.security;
if (routeList[key].swagger) {
objUrl = setDataFromRouteObj(routeList[key].swagger, objUrl);
}
swagger.paths[routeUrl][methodType] = generatePath(objUrl);
} else if (routeList[key].action) {
let filePathToRead = controllerPath + "/" + routeList[key].action;
let actionInputs = getInputs(filePathToRead);
for (const keyai in actionInputs) {
if (actionInputs.hasOwnProperty(keyai)) {
let objAI = actionInputs[keyai];
if(objAI.type == "json") {
delete objAI.type;
}
}
}
objUrl.methodType = methodType;
objUrl.actionInputs = actionInputs;
objUrl.tags = [tag];
objUrl.summary = summary;
objUrl.consumes = ["application/json"];
objUrl.produces = ["application/json"];
objUrl.responses = swaggerConfig.defaults.responses;
objUrl.security = swaggerConfig.defaults.security;
if (routeList[key].swagger) {
objUrl = setDataFromRouteObj(routeList[key].swagger, objUrl);
}
swagger.paths[routeUrl][methodType] = generatePath(objUrl);
}
}
}
swagger.definitions = generateDefinitions();
generateFile(swagger);
}
function setDataFromRouteObj(urlData, objUrl) {
if (urlData.tags) {
objUrl.tags = urlData.tags;
}
if (urlData.summary) {
objUrl.summary = urlData.summary;
}
if (urlData.consumes) {
objUrl.consumes = urlData.consumes;
}
if (urlData.produces) {
objUrl.produces = urlData.produces;
}
if (urlData.responses) {
objUrl.responses = urlData.responses;
}
if (urlData.security) {
objUrl.security = urlData.security;
} else if (!urlData.security) {
delete objUrl.security;
}
if (urlData.parameters) {
objUrl.parameters = urlData.parameters;
}
return objUrl;
}
function addCurlyToRoute(routeUrl) {
// if route has ':id' then we have to convert it to {id}
let urlArray = routeUrl.split(':');
let objUrl = {
routeUrl: '',
pathInputs: [],
originalUrl: routeUrl
}
for (i = 0; i < urlArray.length; i++) {
if (i == 0) {
objUrl.routeUrl = urlArray[i];
} else {
objUrl.pathInputs.push(urlArray[i].split('/')[0]);
if (i == urlArray.length - 1) {
var paths = (urlArray[i]).split('/');
if (paths.length > 1) {
delete paths[0];
objUrl.routeUrl = objUrl.routeUrl + '{' + (urlArray[i]).split('/')[0] + '}' + paths.join('/');
} else {
objUrl.routeUrl = objUrl.routeUrl + '{' + (urlArray[i]).split('/')[0] + '}';
}
} else {
objUrl.routeUrl = objUrl.routeUrl + '{' + (urlArray[i]).split('/')[0] + '}' + '/';
}
}
}
return objUrl;
}
function generatePath(objUrl) {
// get only the first instance of our space splitting
let params = [];
let obj;
let pathInputs = [];
if (objUrl.pathInputs && objUrl.pathInputs.length) {
for (let i = 0; i < objUrl.pathInputs.length; i++) {
for (const key in objUrl.actionInputs) {
if (objUrl.actionInputs.hasOwnProperty(key)) {
if (key == objUrl.pathInputs[i]) {
pathInputs.push({
[key]: objUrl.actionInputs[key]
});
delete objUrl.actionInputs[key];
}
}
}
}
}
pathInputs = Object.assign({}, ...pathInputs);
params = generatePathData(pathInputs, 'path');
if (objUrl.methodType == "post" || objUrl.methodType == "put") {
obj = generateBodyData(objUrl.actionInputs);
params.push(obj);
} else {
let tempObj = JSON.parse(JSON.stringify(generatePathData(objUrl.actionInputs, 'query')));
for (let i = 0; i < tempObj.length; i++) {
params.push(tempObj[i]);
}
}
let path = {
tags: objUrl.tags,
summary: objUrl.summary,
consumes: objUrl.consumes,
produces: objUrl.produces,
responses: objUrl.responses,
security: objUrl.security
};
if (params.length > 0 && params[0] != null) {
path.parameters = params;
}
return path;
}
function generatePathData(actionInputs, type) {
let obj = [];
for (const key in actionInputs) {
if (actionInputs.hasOwnProperty(key)) {
let tempObj = {
"in": type,
name: key,
required: actionInputs[key].required ? actionInputs[key].required : false,
type: actionInputs[key].type ? actionInputs[key].type : '',
description: actionInputs[key].description ? actionInputs[key].description : ''
};
obj.push(tempObj);
}
}
return obj;
}
function generateBodyData(actionInputs) {
let obj = {
name: "body",
in: "body",
required: true,
description: "An object defining our schema for this request",
schema: {
properties: {},
required: []
}
};
for (const key in actionInputs) {
if (actionInputs.hasOwnProperty(key)) {
obj.schema.properties[key] = {
type: actionInputs[key].type === 'ref' ? 'array' : actionInputs[key].type,
};
if (actionInputs[key].description) {
obj.schema.properties[key].description = actionInputs[key].description;
}
if (actionInputs[key].items) {
obj.schema.properties[key].items = actionInputs[key].items;
}
if (actionInputs[key].required) {
obj.schema.required.push(key);
}
}
}
return obj;
}
function generateDefinitions() {
let models = sails.models;
let defintions = {};
for (const key in models) {
// if (key === 'archive') {
// continue;
// }
if (models.hasOwnProperty(key)) {
let model = models[key];
if (model.globalId) {
let objModel = addOnlySpecificKeys(model.attributes);
defintions[model.identity] = {
properties: objModel.attributes,
required: objModel.required
};
}
}
}
return defintions;
}
function generateFile(data) {
// generating folder if not exists
swaggerConfig.pathToGenerateFile = '';
swaggerConfig.fileName = 'swagger.json';
let folders = swaggerConfig.pathToGenerateFile.split('/');
let tempPath = '';
for (let i = 0; i < folders.length; i++) {
if (folders[i] != '') {
tempPath = tempPath + folders[i] + '/';
if (!fs.existsSync(tempPath)) {
var oldmask = process.umask(0);
// console.log(tempPath);
// fs.mkdirSync(path, { recursive: true })
fs.mkdir(tempPath, '0755', function (err) {
process.umask(oldmask);
if (err) {
console.log('generateFile =>', err);
}
});
}
}
}
let fullPath = sails.config.appPath + '/' + swaggerConfig.pathToGenerateFile + swaggerConfig.fileName;
// let fullPath = sails.config.assets + 'assets/swagger/swagger.json';
fs.writeFile(fullPath, JSON.stringify(data), function (err) {
if (err) {
return console.log(err);
}
// console.log("Cheers 🍺 Swagger JSON generated at ", fullPath, ' Access it with http://localhost:' + sails.config.port + '/swagger ');
console.log('Cheers 🍺 Swagger doc generated, Access it with http://localhost:' + sails.config.port + '/swagger ');
});
// let htmlFilePath = sails.config.appPath + '/' + swaggerConfig.pathToGenerateFile + 'index.html';
// // copying html file
// fs.copyFile(__dirname + '/index.html', htmlFilePath, true, (err) => {
// if (err) {
// if (err.code != 'EEXIST') {
// return console.log(err);
// }
// return;
// };
// // console.log('htmlFilePath');
// });
}
function addOnlySpecificKeys(object) {
let objModel = {
attributes: {},
required: []
};
for (const key in object) {
if (object.hasOwnProperty(key)) {
// creating defintions.required array here
if (object[key].required) {
objModel.required.push(key);
}
objModel.attributes[key] = {};
if (object[key].type) {
// if (object[key].type == 'json') {
// object[key].type = 'object'
// }
objModel.attributes[key].type = object[key].type;
}
if (object[key].description) {
objModel.attributes[key].description = object[key].description;
}
if (object[key].defaultsTo) {
objModel.attributes[key].default = object[key].defaultsTo;
}
// if validation found
if (object[key].validations) {
if (object[key].validations.isEmail) {
objModel.attributes[key].format = 'email';
}
if (object[key].validations.maxLength) {
objModel.attributes[key].maxLength = object[key].validations.maxLength;
}
if (object[key].validations.minLength) {
objModel.attributes[key].minLength = object[key].validations.minLength;
}
if (object[key].validations.isIn) {
objModel.attributes[key].enum = object[key].validations.isIn;
}
}
if (object[key].example) {
objModel.attributes[key].example = object[key].example;
}
// if autoMigrations found
if (object[key].autoMigrations) {
if (object[key].autoMigrations.unique) {
objModel.attributes[key].uniqueItems = true;
}
}
}
}
return objModel;
}
function getInputs(path) {
let inputs;
try {
let file = require(path);
inputs = _.clone(file.inputs, true);
} catch (error) {
console.error('getInputs : ', error);
inputs = "";
}
return inputs;
}
function capitalizeString(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
};