npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

joi-data-model

v1.2.1

Published

Modeling with Joi

Downloads

11

Readme

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