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(),
}),
})
},
})
await SampleModel
.build({
details: {
requiredString: 'One',
optionalString: 'Two',
},
})
.validate()
.then(instance => {
})
await SampleModel
.build({
details: {
optionalString: 123,
},
})
.validate()
.catch(error => {
})