Skip to content

Tallysticks/sequelize-joi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sequelize Joi

Allows specifying Joi validation schema for JSONB model attributes in Sequelize.

Installation

npm install --save sequelize-joi

Usage

const Sequelize = require('sequelize')
const sequelize = new Sequelize()
const sequelizeJoi = require('sequelize-joi')
sequelizeJoi(sequelize)

Custom Joi object may be passed:

const Joi = require('joi')
const CustomJoi = Joi.extend(joi => {})
sequelizeJoi(sequelize, { Joi: CustomJoi })

Example

const SampleModel = sequelize.define('SampleModel', {
  details: {
    type: Sequelize.JSONB,
    allowNull: false,
    schema: Joi.object().keys({
      requiredString: Joi.string().required(),
      optionalString: Joi.string().default(null),
      optionalObject: Joi.object().keys({
        requiredSubNumber: Joi.number().required(),
      }),
    })
  },
})

// Validation passes
await SampleModel
  .build({
    details: {
      requiredString: 'One',
      optionalString: 'Two',
    },
  })
  .validate()
  .then(instance => {
    // instance contains default values appended by Joi
  })

// Validation fails
await SampleModel
  .build({
    details: {
      optionalString: 123,
    },
  })
  .validate()
  .catch(error => {
    // error is a 'SequelizeValidationError'
    // error.errors is an array of 'SequelizeValidationErrorItem'
  })

Releases

No releases published

Packages

No packages published