This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tools.js
66 lines (55 loc) · 1.91 KB
/
tools.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
module.exports = require('injectdeps')(
['swagger.spec', 'swagger.metadata', 'swagger.helpers', 'logger'],
function(swaggerSpecification, swaggerMetadataModule, swaggerHelpersModule, logger) {
const log = logger('swagger.app');
function initSwaggerTools(spec, rlOrSO, callback) {
spec.validate.call(spec, rlOrSO, validateCallback.bind({ rlOrSO, callback }));
}
function validateCallback(err, results) {
if (results && hasErrors(results)) {
err = new Error('Swagger document(s) failed validation so the server cannot start');
err.results = results;
}
log.debug('Validation: %s', err ? 'failed' : 'succeeded');
if (err) {
this.callback(err);
}
else {
this.callback(null, {
swaggerMetadata: () => swaggerMetadataModule(this.rlOrSO),
apiDocsJson: () => JSON.stringify(this.rlOrSO, null, 2),
});
}
}
function hasErrors(results) {
let errorCount = results.errors.length;
const apiDeclarations = results.apiDeclarations || [];
const len = apiDeclarations.length;
for(let i = 0; i < len; i++) {
errorCount += apiDeclarations[i].errors.length;
}
return errorCount > 0;
}
function onSwaggerSpecError(err, specVersion, spec) {
if (err.failedValidation === true) {
swaggerHelpersModule.printValidationResults(specVersion, spec, undefined, err.results, true);
}
else {
log.error('Error initializing middleware');
log.error(err.stack);
}
}
return new Promise(function(resolve, reject) {
const spec = swaggerHelpersModule.getSpec(swaggerHelpersModule.getSwaggerVersion(swaggerSpecification), true);
log.info('Identified Swagger version: %s', spec.version);
initSwaggerTools(spec, swaggerSpecification, function (err, tools) {
if (err) {
onSwaggerSpecError(err, spec.version, spec);
reject(err);
}
else {
resolve(tools);
}
});
});
});