Tschema is simple and fastest static type checker for Node.js.
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.
npm install tschema
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() } });
new Schema(schema, options)
You can create schema using tschema.Schema
class.
-
schema
: Any type or object.Available types are:
Number
String
Boolean
- PrimitivesArray
- AnyArray
Object
- AnyObject
(all non-primitive types)Date
Any
- Anything includingnull
,undefined
Optional(Type)
- Given type butnull
,undefined
are allowed[Type]
- Array of given type{ ... }
- Nested objectSchema
- AnotherSchema
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 given type
-
options
: You can pass some options if you want. These options will beerrorProducer
: The error function.dateParser
: Date parser function.
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 } })
});
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
.
- 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