Allows specifying Joi validation schema for JSONB
model attributes in Sequelize.
npm install --save sequelize-joi
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 })
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'
})