Skip to content

Instantly share code, notes, and snippets.

@MiniXC
Created September 1, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MiniXC/146cb24ff0a396d4a0dc1d72762c35fa to your computer and use it in GitHub Desktop.
Save MiniXC/146cb24ff0a396d4a0dc1d72762c35fa to your computer and use it in GitHub Desktop.
const keva = require('keva');
module.exports = (name, json) => {
let schema = {
definitions: {},
title: name,
type: 'object',
properties: json
};
schema.properties = convert(schema.properties, schema.definitions);
return schema;
}
function convert(data, definitions) {
for(let [key, value] of keva(data)) {
if(typeof value === 'string') {
data[key] = {
type: 'string',
default: value
};
} else if(value instanceof Array) {
let distinctTypes = new Set();
for(let element of value) {
distinctTypes.add(element.type);
if(!definitions[element.type]) {
if(typeof element.data === 'string') {
element.data = {
value: element.data
};
}
definitions[element.type] = {
title: element.type,
type: 'object',
additionalProperties: false,
properties: convert(element.data, definitions)
};
definitions[element.type].properties['&type'] = {
type: 'string',
default: element.type
};
}
}
data[key] = {
title: key,
type: 'array',
items: {
anyOf: []
}
};
for(let item of distinctTypes) {
data[key].items.anyOf.push({
'$ref': `#/definitions/${item}`
});
}
} else {
data[key] = {
title: key,
type: 'object',
properties: convert(value, definitions)
}
}
}
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment