forked from apigee-127/swagger-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
351 lines (291 loc) · 10.9 KB
/
Copy pathindex.js
File metadata and controls
351 lines (291 loc) · 10.9 KB
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
/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// Module dependencies
var _ = require('lodash');
var fs = require('fs');
var jjv = require('jjv');
var jjve = require('jjve');
var defaultOptions = {
validator: {
useDefault: false,
useCoerce: false,
checkRequired: true,
removeAdditional: false
}
};
var throwUnsupportedVersion = function (version) {
throw new Error(version + ' is an unsupported Swagger specification version');
};
/**
* Creates a new Swagger specification object.
*
* @param {string} version - The Swagger version
* @param {object} [options] - The specification options
* @param {boolean} [options.validator.useDefault=false] - If true it modifies the object to have the default values for
* missing non-required fields
* @param {boolean} [options.validator.useCoerce=false] - If true it enables type coercion where defined
* @param {boolean} [options.validatorcheckRequired=true] - If true it reports missing required properties, otherwise it
* allows missing required properties
* @param {boolean} [options.validator.removeAdditional=false] - If true it removes all attributes of an object which
* are not matched by the schema's specification
* @constructor
*/
var Specification = function Specification (version, options) {
var docsUrl;
var schemasUrl;
options = _.defaults(options || {}, defaultOptions);
switch (version) {
case '1.2':
docsUrl = 'https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md';
schemasUrl = 'https://github.com/wordnik/swagger-spec/tree/master/schemas/v1.2';
break;
default:
throwUnsupportedVersion(version);
}
this.docsUrl = docsUrl;
this.options = options;
this.schemasUrl = schemasUrl;
this.version = version;
// Load the schema files
this.schemas = {};
fs.readdirSync('./schemas/' + version)
.filter(function (name) {
return name.match(/^(.*)\.json$/);
})
.forEach(function (name) {
this.schemas[name] = require('./schemas/' + version + '/' + name);
}.bind(this));
// Create the validators
this.validators = {};
switch (version) {
case '1.2':
Object.keys(this.schemas).forEach(function (schemaName) {
var validator = jjv(this.options.validator);
var toCompile = [];
// Disable the 'uri' format checker as it's got issues: https://github.com/acornejo/jjv/issues/24
validator.addFormat('uri', function() {
return true;
});
// Since some schemas depend on others, bring them in appropriately
switch (schemaName) {
case 'apiDeclaration.json':
toCompile = [
'dataTypeBase.json',
'modelsObject.json',
'oauth2GrantType.json',
'authorizationObject.json',
'parameterObject.json',
'operationObject.json'
];
break;
case 'authorizationObject.json':
toCompile.push('oauth2GrantType.json');
break;
case 'modelsObject.json':
toCompile.push('dataTypeBase.json');
break;
case 'operationObject.json':
toCompile = [
'dataTypeBase.json',
'authorizationObject.json',
'oauth2GrantType.json',
'parameterObject.json'
];
break;
case 'parameterObject.json':
toCompile.push('dataTypeBase.json');
break;
case 'resourceListing.json':
toCompile = [
'resourceObject.json',
'infoObject.json',
'oauth2GrantType.json',
'authorizationObject.json'
];
break;
}
toCompile.push(schemaName);
toCompile.forEach(function (schemaName) {
this.schemas[schemaName].id = schemaName;
validator.addSchema(schemaName, this.schemas[schemaName]);
}.bind(this));
validator.je = jjve(validator);
this.validators[schemaName] = validator;
}.bind(this));
break;
}
};
var validateModels = function validateModels (spec, resource) {
var modelIds = _.map(resource.models || {}, function (model) {
return model.id;
});
var modelRefs = {};
var primitives = _.union(spec.schemas['dataType.json'].definitions.primitiveType.properties.type.enum,
['array', 'void', 'File']);
var addModelRef = function (modelId, modelRef) {
if (Object.keys(modelRefs).indexOf(modelId) === -1) {
modelRefs[modelId] = [];
}
modelRefs[modelId].push(modelRef);
};
var errors = [];
var warnings = [];
switch (spec.version) {
case '1.2':
// Find references defined in the operations (Validation happens elsewhere but we have to be smart)
if (resource.apis && _.isArray(resource.apis)) {
_.each(resource.apis, function (api, index) {
var apiPath = '$.apis[' + index + ']';
_.each(api.operations, function (operation, index) {
var operationPath = apiPath + '.operations[' + index + ']';
// References in operation type
if (operation.type) {
if (operation.type === 'array' && _.isObject(operation.items) && operation.items.$ref) {
addModelRef(operation.items.$ref, operationPath + '.items.$ref');
} else if (primitives.indexOf(operation.type) === -1) {
addModelRef(operation.type, operationPath + '.type');
}
}
// References in operation parameters
if (operation.parameters && _.isObject(operation.parameters)) {
_.each(operation.parameters, function (parameter, index) {
if (parameter.type && primitives.indexOf(parameter.type) === -1) {
addModelRef(parameter.type, operationPath + '.parameters[' + index + '].type');
} else if (parameter.type === 'array' && _.isObject(parameter.items) && parameter.items.$ref) {
addModelRef(parameter.items.$ref, operationPath + '.parameters[' + index + '].items.$ref');
}
});
}
// References in response messages
if (operation.responseMessages && _.isArray(operation.responseMessages)) {
_.each(operation.responseMessages, function (message, index) {
if (message.responseModel) {
addModelRef(message.responseModel, operationPath + '.responseMessages[' + index + '].responseModel');
}
});
}
});
});
}
// Find references defined in the models themselves (Validation happens elsewhere but we have to be smart)
if (resource.models && _.isObject(resource.models)) {
_.each(resource.models, function (model, name) {
var modelPath = '$.models[\'' + name + '\']'; // Always use bracket notation just to be safe
// References in model properties
if (model.properties && _.isObject(model.properties)) {
_.each(model.properties, function (property, name) {
var propPath = modelPath + '.properties[\'' + name + '\']'; // Always use bracket notation just to be safe
if (property.$ref) {
addModelRef(property.$ref, propPath + '.$ref');
} else if (property.type === 'array' && _.isObject(property.items) && property.items.$ref) {
addModelRef(property.items.$ref, propPath + '.items.$ref');
}
});
}
// References in model subTypes
if (model.subTypes && _.isArray(model.subTypes)) {
_.each(model.subTypes, function (name, index) {
addModelRef(name, modelPath + '.subTypes[' + index + ']');
});
}
});
}
break;
default:
throwUnsupportedVersion(spec.version);
}
// Handle missing models
_.difference(Object.keys(modelRefs), modelIds).forEach(function (missing) {
modelRefs[missing].forEach(function (modelRef) {
errors.push({
code: 'UNRESOLVABLE_MODEL_REFERENCE',
message: 'Model reference could not be resolved: ' + missing,
data: missing,
path: modelRef
});
});
});
// Handle unused models
_.difference(modelIds, Object.keys(modelRefs)).forEach(function (unused) {
warnings.push({
code: 'UNUSED_MODEL',
message: 'Model is defined but is not used: ' + unused,
data: unused,
path: '$.models[\'' + unused + '\']'
});
});
// TODO: Validate subTypes are not cyclical
// TODO: Validate subTypes do not override parent properties
// TODO: Validate subTypes do not include discriminiator
// TODO: Validate discriminitor property exists
// TODO: Validate required properties exist
return {
errors: errors,
warnings: warnings
};
};
/**
* Returns the result of the validation of the Swagger document against its schema.
*
* @param {object} data - The object representing the Swagger document/fragment
* @param {string} [schemaName='apiDeclaration.json'] - The schema name to use to validate the document/fragment
*
* @returns undefined if validation passes or an array of error objects
*/
Specification.prototype.validate = function (data, schemaName) {
if (_.isUndefined(data)) {
throw new Error('data is required');
} else if (!_.isObject(data)) {
throw new TypeError('data must be an object');
}
var errors = [];
var warnings = [];
var schema;
var validator;
var result;
switch (this.version) {
case '1.2':
// Default to 'apiDeclaration.json'
schemaName = schemaName || 'apiDeclaration.json';
break;
default:
throwUnsupportedVersion(this.version);
}
schema = this.schemas[schemaName];
if (!schema) {
throw new Error('schemaName is not valid. Valid schema names: ' + Object.keys(this.schemas).join(', '));
}
// Do structural (JSON Schema) validation
validator = this.validators[schemaName];
result = validator.validate(schema, data);
if (result) {
errors = validator.je(schema, data, result);
}
switch (schemaName) {
case 'apiDeclaration.json':
result = validateModels(this, data);
if (result.errors && _.isArray(result.errors)) {
errors = errors.concat(result.errors);
}
if (result.warnings && _.isArray(result.warnings)) {
warnings = warnings.concat(result.warnings);
}
break;
}
return errors.length === 0 && warnings.length === 0 ? undefined : {errors: errors, warnings: warnings};
};
var v1_2 = module.exports.v1_2 = new Specification('1.2'); // jshint ignore:line