This repository has been archived by the owner on Jan 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.js
executable file
·233 lines (200 loc) · 7.95 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
var fs = require('fs');
var path = require('path');
var through = require('through2');
var gutil = require('gulp-util');
var swaggerParser = require('swagger-parser');
var swaggerTools = require('swagger-tools').specs.v2; // Validate using the latest Swagger 2.x specification
var CodeGen = require('swagger-js-codegen').CodeGen;
var CircularJSON = require('circular-json');
var PLUGIN_NAME = 'gulp-swagger';
module.exports = function gulpSwagger (filename, options) {
// Allow for passing the `filename` as part of the options.
if (typeof filename === 'object') {
options = filename;
filename = options.filename;
}
options = options || {};
// expose options from swagger-parser
// https://github.com/BigstickCarpet/swagger-parser/blob/master/docs/options.md
var parserSettings = options.parser || {};
// Flag if user actually wants to use codeGen or just parse the schema and get json back.
var useCodeGen = typeof options.codegen === 'object';
var codeGenSettings = options.codegen || {};
// If user wants to use the codeGen
if (useCodeGen) {
// Allow for shortcuts by providing sensitive defaults.
codeGenSettings.type = codeGenSettings.type || 'custom'; // type of codeGen, either: 'angular', 'node' or 'custom'.
codeGenSettings.moduleName = codeGenSettings.moduleName || 'API';
codeGenSettings.className = codeGenSettings.className || 'API';
// If codeGen is of type custom, user must provide templates.
if (codeGenSettings.type === 'custom' && !codeGenSettings.template) {
throw new gutil.PluginError(PLUGIN_NAME, 'Templates are mandatory for a custom codegen');
}
// Shortcut: Allow `template` to be a string passing a single template file.
else if (typeof codeGenSettings.template === 'string') {
var template = fs.readFileSync(codeGenSettings.template, 'utf-8');
if ( typeof template !== 'string' || !template.length ) {
throw new gutil.PluginError(PLUGIN_NAME, 'Could not load template file');
}
codeGenSettings.template = {
class: template,
method: '',
request: ''
};
}
// Regular codeGen template object, but allowing for missing templates.
// (e.g. use case: if `request` is too simple, there's no need for a dedicated template file)
else if (typeof codeGenSettings.template === 'object') {
['class', 'method', 'request']
.forEach(function loadTemplateFile (tmpl) {
var template = codeGenSettings.template[tmpl];
if (typeof template !== 'string' || !template.length) {
return (codeGenSettings.template[tmpl] = '');
}
template = fs.readFileSync(template, 'utf-8');
if (typeof template !== 'string' || !template.length) {
throw new gutil.PluginError(PLUGIN_NAME, 'Could not load ' + tmpl + ' template file. Please make sure path to file is correct.');
}
codeGenSettings.template[tmpl] = template;
});
}
}
return through.obj(function throughObj (file, encoding, callback) {
var _this = this;
if ( file.isStream() ) {
throw new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported');
}
// Load swagger main file resolving *only* external $refs and validate schema (1st pass).
// We keep internal $refs intact for more accurate results in 2nd validation pass bellow.
swaggerParser.dereference(file.history[0], {
$refs: { internal: false }
}, function parseSchema (error, swaggerObject) {
if ( error ) {
callback(new gutil.PluginError(PLUGIN_NAME, error));
return;
}
// Re-Validate resulting schema using different project (2nd pass), the
// reason being that this validator gives different (and more accurate) resutls.
swaggerTools.validate(swaggerObject, function validateSchema (err, result) {
if (err) {
callback(new gutil.PluginError(PLUGIN_NAME, err));
return;
}
if ( typeof result !== 'undefined' ) {
if ( result.errors.length > 0 ) {
gutil.log(
gutil.colors.red([
'',
'',
'Swagger Schema Errors (' + result.errors.length + ')',
'--------------------------',
result.errors.map(function (err) {
return '#/' + err.path.join('/') + ': ' + err.message +
'\n' +
JSON.stringify(err) +
'\n';
}).join('\n'),
''
].join('\n')),
''
);
}
if ( result.warnings.length > 0 ) {
gutil.log(
gutil.colors.yellow([
'',
'',
'Swagger Schema Warnings (' + result.warnings.length + ')',
'------------------------',
result.warnings.map(function (warn) {
return '#/' + warn.path.join('/') + ': ' + warn.message +
'\n' +
JSON.stringify(warn) +
'\n';
}).join('\n'),
''
].join('\n')),
''
);
}
if ( result.errors.length > 0 ) {
callback(new gutil.PluginError(PLUGIN_NAME, 'The Swagger schema is invalid'));
return;
}
}
// Now that we know for sure the schema is 100% valid,
// if there is not file name...
if (!filename) {
// ...return validated file to gulp without making changes to it
return _this.push(file);
}
// ...or continue by dereferencing internal $refs as well.
swaggerParser.dereference(swaggerObject, parserSettings, function parseSchema (error, swaggerObject) {
if (error) {
callback(new gutil.PluginError(PLUGIN_NAME, error));
return;
}
var fileBuffer;
if ( useCodeGen ) {
var codeGenFunction = 'get' +
codeGenSettings.type[0].toUpperCase() +
codeGenSettings.type.slice(1, codeGenSettings.type.length) +
'Code';
codeGenSettings.esnext = true;
codeGenSettings.swagger = swaggerObject;
delete codeGenSettings.type;
codeGenSettings.mustache = codeGenSettings.mustache || {};
// Allow swagger schema to be easily accessed inside templates.
codeGenSettings.mustache.swaggerObject = swaggerObject;
codeGenSettings.mustache.swaggerJSON = JSON.stringify(swaggerObject);
// Allow each individual JSON schema to be easily accessed inside templates (for validation purposes).
codeGenSettings.mustache.JSONSchemas = JSON.stringify(
Object.keys(swaggerObject.paths)
.reduce(function reducePaths (newPathCollection, currentPath) {
var pathMethods = swaggerObject.paths[currentPath] || {};
var pathSchemas = Object.keys(pathMethods)
.reduce(function reduceMethods (newMethodCollection, currentMethod) {
var methodParameters = (pathMethods[currentMethod].parameters || [])
.filter(function filterBodyParameter (parameter) {
return parameter.in === 'body';
})[0] || {};
var methodResponses = pathMethods[currentMethod].responses || {};
var methodSchemas = {
request: methodParameters.schema,
responses: Object.keys(methodResponses)
.reduce(function reduceMethods (newResponsesCollection, currentResponse) {
var responseSchema = methodResponses[currentResponse].schema || {};
newResponsesCollection[currentResponse] = responseSchema;
return newResponsesCollection;
}, {})
};
newMethodCollection[currentMethod] = methodSchemas;
return newMethodCollection;
}, {});
newPathCollection[currentPath] = pathSchemas;
return newPathCollection;
}, {})
);
fileBuffer = CodeGen[codeGenFunction](codeGenSettings);
}
else {
try {
fileBuffer = JSON.stringify(swaggerObject);
}
catch (error) {
fileBuffer = CircularJSON.stringify(swaggerObject);
}
}
// Return processed file to gulp
_this.push(new gutil.File({
cwd: file.cwd,
base: file.base,
path: path.join(file.base, filename),
contents: new Buffer(fileBuffer)
}));
callback();
}); // swaggerParser.dereference (internal $refs)
}); // swaggerTools.validate
}); // swaggerParser.dereference (external $refs)
}); // return through.obj
};