Schema to Yup schema
Build a Yup schema from a JSON Schema, GraphQL schema (type definition) or any other similar type/class and field/properties model or schema :)
The builder currently supports the most commonly used JSON Schema layout and GraphQL type definition exports using graphSchemaToJson (see GraphQL schema).
It also supports some extra convenience schema properties that make it more "smooth" to define validation requirements declaratively (see below).
According to the JSON schema specs, you are free to add extra metadata to the field schema definitions beyond those supported "natively".
Quick start
Install
npm install json-schema-to-yup -S
or yarn add json-schema-to-yup
Use
const schema = $schema: "http://json-schema.org/draft-07/schema#" $id: "http://example.com/person.schema.json" title: "Person" description: "A person" type: "object" properties: name: description: "Name of the person" type: "string" email: type: "string" format: "email" fooorbar: type: "string" matches: "(foo|bar)" age: description: "Age of person" type: "number" exclusiveMinimum: 0 required: true characterType: enum: "good" "bad" enum_titles: "Good" "Bad" type: "string" title: "Type of people" propertyOrder: 3 required: "name" "email"; const config = // for error messages... errMessages: age: required: "A person must have an age" email: required: "You must enter an email address" format: "Not a valid email address" ; const buildYup = ;const yupSchema = ;// console.dir(schema)const valid = await yupSchema; console;// => {valid: true}
This would generate the following Yup validation schema:
const schema = yupobjectshape name: yup age: yup ;
Note the "required": true
for the age
property (not natively supported by JSON schema).
Types and keys
Mixed (any type)
strict
default
nullable
required
notRequired
oneOf
(enum
)notOneOf
Array
ensure
compact
items
(of
)maxItems
(max
)minItems
(min
)
Boolean
No keys
Date
maxDate
(max
)minDate
(min
)
Number
integer
moreThan
(exclusiveMinimum
)lessThan
(exclusiveMaximum
)positive
negative
min
(minimum
)max
(maximum
)truncate
round
Object
camelCase
constantCase
noUnknown
(propertyNames
)
String
minLength
(min
)maxLength
(max
)pattern
(matches
orregex
)email
(format: 'email'
)url
(format: 'url'
)lowercase
uppercase
trim
Complex example
Here a more complete example of the variations currently possible
}
Custom models
This library now also supports non JSON schema models. See the types/defaults
mappings.
types/defaults/json-schema.js
moduleexports objproperties objtype objname || objtitle obj objtype === "string" objtype === "array" objtype === "integer" objtype === "boolean" "date" "date-time" objtype === "string" && defaults objtype === "number" || defaults objtype === "object" objrequired;
GraphQL schema
To support another model, such as GraphQL schema (type definitions) via graphSchemaToJson
Person
Person: name: 'Person' fields: name: type: 'String' directives: constraints: minLength: 2 isNullable: false isList: false directives: {} type: 'Object' implements:
Create a map of methods to match your model layout:
const typeDefConf = objfields objtype objname objdirectives || {}constraints || {} objtype === "String" objisList objtype === "Int" objtype === "Boolean" objtype === "Date" || objdirectivesdate objtype === "Int" || objtype === "Float" objtype === "Object" !objisNullable;
Please note that getConstraints
can be used to control where the constraints of the field will be taken from (depending on the type of model/schema or your preference).
Pass overrides to match your model in config
as follows:
const schema = ;
The type definition mappings above are already built-in and available.
To switch the schema type, pass schemaType
in config as follows.
const schema = ;
Feel free to make PRs to make more common schema models conveniently available!
Custom logs and error handling
You can enable logging py passing a log
option in the config
argument. If set to true, it will by default assign the internal log function to console.log
const schema = ;
You can also pass a log function in the log
option to handle log messages and an err
option with a custom error handler function.
See Custom errors in Node for how to design custom errors
{} const schema =
Customization
You can supply a createYupSchemaEntry
function as an entry in the config
object.
This function will then be used to build each Yup Schema entry in the Yup Schema being built.
Use the Yup Type classes such as types.YupArray
to act as building blocks or create your own custom logic as you see fit.
Customization example
const YupSchemaEntry buildYup types = ; YupArray // ... // ... { const builder = key value config; buildertypes ; return builder;} // use some localized error messagesconst messages = i18n; const yupSchema = ;
Extend Yup API to bridge other validators
You can use extendYupApi
to extend the Yup API with extra validation methods:
const validator = ;const extendYupApi = ; // by default extends with string format validation methods of validator// See https://www.npmjs.com/package/validator;
You can optionally pass in a custom validator
and a constraints map of your choice.
You can either extend the default constraints or override them with your own map.
PS: Check out src/validator-bridge
for more many options for fine control
const myValidator = ;const constraints = "creditCard" "currency" name: "hash" opts: "algo" ;; const buildYup = ;// type def sample schema, using credit-card format validatorconst schema = name: "BankAccount" fields: accountNumber: type: "String" format: "credit-card" ; // opt in to use generic string format validation, via format: true config optionconst yupSchema = ;// ...do your validationconst valid = await yupSchema;
Now the bridge includes tests. Seems to work ;)
Subclassing
You can sublass YupBuilder
or any of the internal classes to create your own custom infrastructure to suit your particular needs, expand with support for extra features etc.
const YupBuilder = ; // ... custom overrides etc const builder = schema config;const yupSchema = builder;// ...
Error messages
You can pass an errMessages
object in the optional config
object argument with key mappings for your custom validation error messages.
Internally the validator error messages are resolved with the instance method valErrMessage
(from Mixed
class)
{ const not notOneOf = thisvalue const $oneOf = notOneOf || not && notenum || notoneOf $oneOf && this base return this }
The key entries can be either a function, taking a value
argument or a static string.
Here are some of the defaults that you can override as needed.
const errValKeys = "oneOf" "enum" "required" "notRequired" "minDate" "min" "maxDate" "max" "trim" "lowercase" "uppercase" "email" "url" "minLength" "maxLength" "pattern" "matches" "regex" "integer" "positive" "minimum" "maximum"; const defaults = keys;
Custom validation messages using select defaults
const buildYup types = ;const defaults = types; const myErrMessages = ;const valKeys = "lowercase" "integer"; // by default Yup built-in validation error messages will be used if not overridden hereconst errMessages = ...defaults myErrMessages; const yupSchema = ;
Adding custom constraints
See the number
type for the current best practice to add type constraints.
For simple cases: use addConstraint
from the superclass YupMixed
{ return this; }
For types with several of these, we should map through a list or map to add them all.
{ return this; } { return this; } { return this; }
Can be rewritten to use conventions, iterating a map:
{ Object; } { return simple: "required" "notRequired" "nullable" value: "default" "strict" ; }
For more complex contraints that:
- have multiple valid constraint names
- require validation
- optional transformation
You can create a separate Constraint
subclass, to offload and handle it all separately.
Here is a sample RangeConstraint
used by number.
{ supertyper; } get return moreThan: "exclusiveMinimum" "moreThan" lessThan: "exclusiveMaximum" "lessThan" max: "maximum" "max" min: "minimum" "min" ;
Instead of wrapping a Constraint
you can call it directly with a map
// this would be an instance such as YupNumber// map equivalent to $map in the RangeConstraint { return ;}
For the core type constraint class (such as YupNumber
) you should now be able to simplify it to:
{ return "range" "posNeg" "integer"; } { thisenabled; super; return this; }
The following constraint classes are available for use:
NumericConstraint
StringConstraint
RegExpConstraint
DateConstraint
Currently only YupNumber
has been (partly) refactored to take advantage of this new infrastructure. Please help refactor the rest!
YupNumber
also has the most unit test coverage, used to test the current infrastructure!
Similar projects
- JSON schema to Elastic Search mapping
- JSON Schema to GraphQL types with decorators/directives
- JSON Schema to Mongoose schema
- JSON Schema to MobX State Tree types
- Convert JSON schema to mongoose 5 schema
The library JSON Schema model builder is a powerful toolset to build a framework to create any kind of output model from a JSON schema.
If you enjoy this declarative/generator approach, try it out!
Testing
Uses jest for unit testing.
- Have unit tests that cover most of the constraints supported.
- Could use some refactoring using the latest infrastructure (see
NumericConstraint
) - Please help add more test coverage and help refactor to make this lib even more awesome :)
Development
Current development is taking place on refactoring branch.
On his branch:
- all the code has been converted to TypeScript
- constraint classes for String, Numeric, RegExp etc.
- Validator building has been extracted so you can add support for any Validator, such as Forg
- more...
If you would like to further improved this library or add support for more validators than Yup, please help on this branch. Cheers!
Ideas and suggestions
Please feel free to come with ideas and suggestions on how to further improve this library.
Author
2018 Kristian Mandrup (CTO@Tecla5)
License
MIT