Created
September 1, 2017 13:58
-
-
Save MiniXC/146cb24ff0a396d4a0dc1d72762c35fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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