Plain JavaScript objects with runtime type guarantees
npm install @studio/schema
🧩 Plain JavaScript objects with runtime type guarantees. For node and
browsers.
Defining a schema:
``js
const { schema, object, string, integer, opt } = require('@studio/schema');
/**
* @typedef {ReturnType
*/
const person = schema(
object({
name: string, // mandatory
age: opt(integer) // optional
})
);
`
The schema is a function that can be used to validate a given object. It throws
if non-optional properties are missing, a value has the wrong type, or
undeclared properties are present.
`js
person({ name: 123 }); // throws
person({ name: 'Test', customer: true }); // throws
person({ name: 'Test', age: true }); // throws
person({ name: 'Test', age: 7.5 }); // throws
person({ name: 'Test' }); // ok
person({ name: 'Test', age: 7 }); // ok
`
Validators are functions that verify values and objects. A validator function
returns false if a value doesn't meet the expectation. Studio Schema comes
with a set of pre-defined validators for primitive types, enums, objects,
arrays and maps. Validators can be nested and reused:
`js
const { schema, literal, string, object, array } = require('@studio/schema');
const status = literal('LOADING', 'LOADED', 'SAVING', 'SAVED');
const person = object({
first_name: string,
last_name: string,
tags: array(string)
});
/**
* @typedef {import('@studio/schema').Infer
*/
const personModel = schema(object({ status, person }));
`
A reader validates a given object and returns a [Proxy][1] that makes the
object read-only and verifies that only defined properties are accessed.
`js
const person = person.read({ name: 'Test', age: 7 });
const name = person.name; // ok
const age = person.age; // ok
const customer = person.customer; // throws
person.name = 'Changed'; // throws
`
A writer accepts an empty or partial object and returns a [Proxy][1] that
validates any accessed, assigned or deleted properties. To verify that no
non-optional properties are missing, use mySchema.verify(writer).
`js
const alice = person.write({ name: 'Alice' });
alice.customer = true; // throws
alice.name = 'Changed'; // ok
alice.age = 7; // ok
`
All schema validation errors have a code property with the valueE_SCHEMA.
Validators and schemas creates TypeScript types from the given structure.
Resolve the types like this:
`js
/**
* @typedef {import('@studio/schema').Infer
*/
const mySchema = schema(someValidator);
/**
* @typedef {import('@studio/schema').Infer
*/
const myLiteral = literal('foo', 'bar');
`
This module exports the schema function which carries the entire API, so you
can require it in two ways:
`js
const schema = require('@studio/schema');
const person = schema({ name: schema.string });
`
With [destructuring][2]:
`js
const { schema, string } = require('@studio/schema');
const person = schema({ name: string });
`
- schema(validator[, options]): Returns a new schema with the given validator.validator
The validator to use for the schema. These options are supported:error_code
- : The code property to define on errors. Defaults toE_SCHEMA
.defined
- : Is a validator that accepts any value other than undefined.boolean
- : Is a validator that accepts true and false.number
- : Is a validator that accepts finite number values.number.min(min)
- : Is a validator that accepts finite number values >= min.number.max(max)
- : Is a validator that accepts finite number values <= max.number.range(min, max)
- : Is a validator that accepts finite number values >=min
and <= max.integer
- : Is a validator that accepts finite integer values.integer.min(min)
- : Is a validator that accepts finite integer values >=min
.integer.max(max)
- : Is a validator that accepts finite integer values <=max
.integer.range(min, max)
- : Is a validator that accepts finite integer valuesmin
> = and <= max.string
- : Is a validator that accepts string values.string.regexp(re)
- : Is a validator that accepts string values matching thestring.length.{min,max,range}
given regular expression.
- : Verifies the string length with an integerliteral(value_1, value_2, ...)
validator.
- : Returns a validator that matches against aall(validator_1, validator_2, ...)
list of primitive values. Can be used to define constants or enumerations.
- : Returns a validator where all of theone(validator_1, validator_2, ...)
given validators have to match.
- : Returns a validator where one of theopt(validator)
given validators has to match.
- : Returns an optional validator.object(properties)
- : Returns an object validator. The given object mapsobject.any
object keys to validators.
- : Is a validator that accepts arbitrary object values.array(itemValidator)
- : Returns an array. Each element in the array has toarray.any
match the given validator..
- : Is a validator that accepts arbitrary array values.map(keyValidator, valueValidator)
- : Returns a map validator for key-valuekeyValidator
pairs where and valueValidator are the validators for thevalidator(test[, toString])
object key and value pairs.
- : Creates a custom validator for the giventest
function. The optional toString argument can be a function that
returns a string, or a string defining the validator name used in error
messages. Defaults to .E_SCHEMA
- : The code property exposed on schema validation errors.
Note that all validator functions are also exposed on schema.
The schema created by schema(validator) is a function that throws aTypeError if the given value does not match the validator, and returns theobject
value otherwise. For and array, the schema also allows to create
proxy objects that validate reading, assigning and deleting properties:
- reader = mySchema.read(data[, options]): Creates a schema compliant readererror_code
for the given data. If the given data does not match the schema, an exception
is thrown. The returned reader throws on any property modification or on an
attempt to read an undefined property. These options are supported:
- : The code property to define on errors. Defaults toE_SCHEMA
.writer = mySchema.write([data[, options]])
- : Creates a writer with optionalerror_code
initial data. If the given data does not match the schema, an exception is
thrown. The returned writer throws on undefined property modification, if an
assigned value is invalid, or on an attempt to read an undefined property.
These options are supported:
- : The code property to define on errors. Defaults toE_SCHEMA
.data = mySchema.verify(writer)
- : Checks if any properties are missing in thedata = reader_or_writer.toJSON()
given writer and returns the unwrapped data. Throws if the given object is
not a schema writer.
- : returns the original object.
Note that schema readers and writers can be safely used with JSON.stringify`.
MIT
Made with ❤️ on 🌍
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment