This is a plugin to use Joi with Hemera
npm install hemera-joi

This is a plugin to use Joi for request/response validation.
``js`
const hemera = new Hemera(nats)
hemera.use(require('hemera-joi'))
The primary purpose of joi is to validate the incoming request. You can define your validation schema with the joi$ property or inline.
`js
let Joi = hemera.joi
// inline
hemera.add(
{
topic: 'math',
cmd: 'add',
a: Joi.number().required()
},
(req, cb) => {
cb(null, req.a + req.b)
}
)
// with joi$ property`
hemera.add(
{
topic: 'math',
cmd: 'add',
joi$: Joi.object().keys({ a: Joi.number().required() })
},
(req, cb) => {
cb(null, req.a + req.b)
}
)
You can validate the response payload as well if you use the postJoi$ property. Response error isn't validated but must be from type Error.
If a field is present in the schema (and is not required) but it is not present in the object to validate, joi will not write it in the final payload.
`js
let Joi = hemera.joi
hemera.add(
{
topic: 'math',
cmd: 'add',
preJoi$: {
a: Joi.number().required()
},
postJoi$: {
foo: Joi.number().default(500)
}
},
(req, cb) => {
cb(null, { foo: req.a + req.b })
}
)
`
You can modify the joi validation settings with the pre and post plugin options.
`js`
const hemera = new Hemera(nats)
hemera.use(
require('hemera-joi', {
patternKeys: {
default: 'joi$',
pre: 'preJoi$',
post: 'postJoi$'
},
// joi settings
pre: { allowUnknown: true },
post: { stripUnknown: true }
})
)
You can define base schemas which enrich your existing pre/post schemas. In that way you can ensure that a specific property is always send or if you want to
set the joi property allowUnknown to false.
`js``
hemera.use(HemeraJoi, {
basePreSchema: {
topic: Joi.string().required(),
cmd: Joi.string().required()
},
basePostSchema: {
userId: Joi.number().required()
},
pre: { allowUnknown: false }
})
* .joi