tschema
v1.1.0
Published
Simple and fastest static type checker for Node.js.
Downloads
53
Readme
Tschema
Tschema is simple and fastest static type checker for Node.js.
Why it's the Fastest?
Because Tschema compiles scheme validation code into single static function - containing only if
statements.
So Tschema doesn't parse the schema at runtime. It only consumes O(1) on validation time.
Install
npm install tschema
Example
const { Schema, Optional } = require('tschema');
const User = new Schema({
name: String,
age: Number,
friends: [String],
info: {
createdAt: Date,
lastLoginedAt: Optional(Date),
},
});
User.validate({ name: 'John', age: 20, friends: ['foo', 'bar'], info: { createdAt: Date.now() } });
Documentations
Defining a Schema
new Schema(schema, options)
You can create schema using tschema.Schema
class.
schema
: any type or object.Available types are:
Number
String
Boolean
- primitivesArray
- any arrayObject
- any objectDate
Any
- anythingOptional(Type)
- optional (nullable)[Type]
- array of some type{ ... }
- nested objectSchema
- another schema
Instead of giving constructors or
Optional
, you can define schema using Flow style.const User = new Schema({ name: 'string', age: 'number', friends: 'string[]', createdAt: '?date', });
'number'
,'string'
,'boolean'
- primitives'array'
,'object'
,'date'
,'any'
'?type'
- optional'type[]'
- array of some type
options
: You can pass some options if you want. These options will beerrorProducer
: The error function.dateParser
: Date parser function.
Customizing a Schema
Change error behavior
In default, Schema#validate
will throw an Error
if given value is invalid.
errorProducer: (field, type) => `throw Error('${field} is not a ${type}.')`
You can change this behavior by passing your own errorProducer
to options
.
For example, if you want to return some object if Schema#validate
fails, you need to do like this:
const User = new Schema({ ... }, {
errorProducer: (field, type) => ({ error: { name: field, tobe: type } })
});
Use custom date parser
In default, Tschema parses Date
type using new Date
.
dateParser: (value) => new Date(value)
You can replace this parser by passing your own dateParser
to options
.
TODO
- Named Schema for self-embedding (ex:
User = new Schema('User', { author: 'User' })
) - Strict mode (fails at
verify
if given value has fields undefined on schema) - Integration with ORM/ODM libraries (
sequelize
,mongorito
,mongoose
, ...) - TypeScript, Flow support