Coder Social home page Coder Social logo

joi-data-model's Introduction

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

joi-data-model's People

Contributors

ctdio avatar

Stargazers

Chris Godwin avatar James Beavers avatar

Watchers

Chris Godwin avatar  avatar

Forkers

kevnz

joi-data-model's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.