Skip to content

ctdio/joi-data-model

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

joi-data-model

Build Status Coverage Status

Simple data modeling that uses Joi for performing validation.

Installation

npm install joi-data-model

Usage

A minimal example:

const Joi = require('Joi')
const joiDataModel = require('joi-data-model')

const schema = { name: Joi.string() }

const Person = joiDataModel.define(schema)

const person = new Person({
  name: 1234
})
// ^^^ throws a validation error

Defining a model

Models are defined using the define function exposed by joi-data-model.

define(schema [, validationOptions])

The schema that needs to be passed in is the same input that would normally be passed into Joi.object().keys().

Example schema:

const personSchema = {
  name: Joi.string(),
  age: Joi.number().integer()
}

To define a model class, simply just pass in the schema to the exposed define function.

const Person = joiDataModel.define(personSchema)

Validation options that are normally passed as the second option of Joi.validate can be passed to define.

Example:

const Person = joiDataModel.define(personSchema, {
  abortEarly: false
})

Instantiating a model

You can create a new instance of model much like how a class instance is instantiated.

const person = new Person()

Additionally, an object can be passed into the model's constructor for validation.

const person = new Person({
  name: 'Some name',
  age: 123456
})

If the data does not pass validation, an error will be thrown.

const person = new Person({
  name: {
    totally: 'not a string'
  }
})
// ^^^ this will throw a validation error

Of course, if the schema has required attributes, missing data will cause errors to be thrown.

For example with the following model:

const Person = joiDataModel.define({
  name: Joi.string().required()
})

Performing ether of the following will throw a validation error:

const person = new Person()
const person = new Person({})

Using models

Model instances are designed to be a non-intrusive wrapper for data that ensures that the schema is always followed.

Using the following model:

const Car = joiDataModel.define({
  make: Joi.string(),
  model: Joi.string(),
  year: Joi.number().integer()
})

And the following instance:

const car = new Car({
  make: 'Mazda',
  model: 'Miata',
  year: 1994
})

You can access data defined on the schema like you would for a regular object.

const { make, model, year } = car

// make === 'Mazda'
// model === 'Miata'
// year === 1994

You can also set data on the model.

car.make = 'Honda' // valid

However setting the data to a value that does not match the schema will cause a validation error.

car.year = 'not a valid year'
// ^^^ throws a validation error

Important Note: Setting values nested deep within the model (Ex. modelInstance.value.nestedValue = 'blah'), bypasses validation. Setters are only defined for properties on the surface of the model. If models need to be mutated, be sure to either tread carefully or keep schemas definitions relatively flat.

To get a pure javascript object clone of the data stored within the model, you can call the instance's toJSON function.

const object = car.toJSON()
console.log(Object.getPrototypeOf(object) === Object.prototype) // true

Performing simple validation

Don't need a model instance? Models provide a static validate method that performs validation using the schema and validation options used when defining the model.

Model.validate(input)
const personSchema = { name: Joi.string() }
const options = { abortEarly: false }
const Model = joiDataModel.define(personSchema, options)

const validatedData = Model.validate({ name: 'string' }) // not a model instance

This is the equivalent of calling Joi.validate(input, schema, validationOptions).

Extending models

Since a Model is just a Class, it is easy to extend functionality.

Example:

const schema = { name: Joi.string() }

class BaseModel extends joiDataModel.define(schema) {
  stringify () {
    return JSON.stringify(this)
  }
}

const model = new BaseModel({ name: 'some name' })

console.log(model.stringify()) // prints '{"name":"some name"}'

The schema can be extended/overridden by using the static extend method.

Model.extend(schema [, validationOptions ])
const ageSchema = { age: Joi.number() }

const ExtendedModel = BaseModel.extend(ageSchema)

const model = new ExtendedModel({
  name: 'some one',
  age: 25
})
// ^^ this is a valid model
console.log(model instanceof BaseModel) // prints true
console.log(model.stringify()) // prints '{"name":"some name","age":25}'

Todo

  • Immutable model instances

About

Simple models using Joi for validation

Resources

Stars

Watchers

Forks

Packages

No packages published