-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
91 lines (82 loc) · 2.7 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
'use strict';
const Ajv = require('ajv');
const toOpenApi = require('json-schema-to-openapi-schema');
const OpenAPISchemaValidator = require('openapi-schema-validator').default;
const debug = require('debug')('ajvToSwagger');
const ajvLoger = {
log: (...args) => { debug('LOG', ...args); },
warn: (...args) => { debug('WARN', ...args); },
error: (...args) => { debug('ERROR', ...args); },
};
const ajv = new Ajv({ verbose: true, allErrors: true, logger: ajvLoger });
const swaggerBase = require('./files/swaggerDraft.json');
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function isPrimitive(test) {
return (test !== Object(test));
}
function fixPatternProperties(obj) {
const defaultValue = obj instanceof Array && [] || {};
return Object.entries(obj).reduce((res, [name, value]) => {
if (name === 'additionalProperties') {
if (!res.additionalProperties) {
res.additionalProperties = value;
}
return res;
}
if (name === 'patternProperties') {
res.additionalProperties = fixPatternProperties(Object.values(value)[0]);
// eslint-disable-next-line prefer-destructuring
res['x-pattern'] = Object.keys(value)[0];
return res;
}
if (isPrimitive(value)) {
res[name] = value;
return res;
}
res[name] = fixPatternProperties(value);
return res;
}, defaultValue);
}
function convertSchema(schema, options = { validate: true }) {
debug('compiling schema via ajv');
try {
ajv.compile(schema);
} catch (err) {
debug('AJV validation failed, schema is invalid');
throw err;
}
debug('schema is valid');
debug('converting patternProperties');
const propertiesConverted = fixPatternProperties(schema);
const convertedSchema = toOpenApi(Object.assign({}, propertiesConverted, { $schema: 'http://json-schema.org/draft-07/schema#' }));
if (!options.validate) {
return convertedSchema;
}
const validator = new OpenAPISchemaValidator({
// optional
version: 3,
// optional
version2Extensions: {
/* place any properties here to extend the schema. */
},
// optional
version3Extensions: {
/* place any properties here to extend the schema. */
},
});
const swaggerDoc = clone(swaggerBase);
swaggerDoc.paths['/get/some/'].get.responses['200'].content['application/json'].schema = convertedSchema.schema;
const errors = validator.validate(swaggerDoc);
if (errors && errors.length) {
debug('There were errors while validating converted schema as open api:');
debug(JSON.stringify(errors, null, 3));
throw new Error(JSON.stringify(errors));
}
debug('validation of coverted schema okay!');
return convertedSchema;
}
module.exports = {
convertSchema,
};