better-schemas

1.0.1 • Public • Published

Build Status Coverage Status

better-schemas

A simple schema validation implementation for NodeJs.

Usage

const Schema = require('schema-js')

Create a schema for well-defined structures

const postSchema = new Schema('user.post', {
  name : { type: String, required: true }, // throws when not set
  description: String // optional
})
 
function handlePOST(req, res, next) {
  var data = req.body
  try {
    postSchema.validate(data)
    res.send('looks good!')
  } catch(e) {
    next(e)
  }
}

Define your own base-types

const MyType = new Schema.Type('my type', n => n == 1)
if(MyType.validate(1)) console.log('success!')

Define your own Schemas

const MySchema = new Schema('my-schema', {
  key : { type:Schema.Types.Any, default: 'value' }, // sets default when undefined
  arrays: [{type: String}],
  simple_types: Number,
  helper_types: Schema.Types.Integer,
  name : { type:String, required: true } 
})
 
var data = MySchema.validate({ key: undefined, arrays: ['are', 'great'] }) // undefined & null are replaced by defaults

Retrieve schemas by name

const MySchema = Schema.get('my-schema')

Create a nested Schema

const MySchema = Schema.get('my-schema')
const MyOtherSchema = new Schema('complex-schema', {
  name: { type: String, required: true },
  data: MySchema
})

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.1
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.1
    1

Package Sidebar

Install

npm i better-schemas

Weekly Downloads

1

Version

1.0.1

License

ISC

Last publish

Collaborators

  • matutter