Joi -> JSON Schema Converter (support joi v16.0)
npm install @yeongjet/joi-to-json-schemajs
var joi = require('joi'),
convert = require('joi-to-json-schema'),
joiSchema = joi.object({
'name': joi.string().required().regex(/^\w+$/),
'description': joi.string().optional().default('no description provided'),
'a': joi.boolean().required().default(false),
'b': joi.alternatives().when('a', {
is: true,
then: joi.string().default('a is true'),
otherwise: joi.number().default(0)
})
});
convert(joiSchema);
`
which will produce:
`js
{ type: 'object',
properties:
{ name: { type: 'string', pattern: '^\\w+$' },
description: { default: 'no description provided', type: 'string' },
a: { type: 'boolean', default: false },
b: { oneOf: [ { default: 'a is true', type: 'string' }, { type: 'number', default: 0 } ] } },
additionalProperties: false,
required: [ 'name', 'a' ] }
`
JSDOC
`javascript
/**
* Converts the supplied joi validation object into a JSON schema object,
* optionally applying a transformation.
*
* @param {JoiValidation} joi
* @param {TransformFunction} [transformer=null]
* @returns {JSONSchema}
*/
export default function convert(joi,transformer=null) {
// ...
};
/**
* Joi Validation Object
* @typedef {object} JoiValidation
*/
/**
* Transformation Function - applied just before convert() returns and called as function(object):object
* @typedef {function} TransformFunction
*/
/**
* JSON Schema Object
* @typedef {object} JSONSchema
*/
`
Notes
Joi's conditional form, i.e. .when('name',{is:cond,then:joi,otherwise:joi}), is evaluated at runtime
and since, from the perspective of the schema, there is no way of knowing what the condition might resolve to, this
module takes the position that it should provide _all possible resolutions_ in a JSON Schema oneOf:[]` clause.