hemera-ajv
v1.0.2
Published
This is a plugin to use Ajv (JSON-Schema) for request validation.
Downloads
10,121
Maintainers
Readme
Hemera-ajv package
This is a plugin to use Ajv (JSON-Schema) for request/response validation.
Usage
const hemera = new Hemera(nats)
hemera.use(require('hemera-ajv'))
Request validation
The primary purpose of ajv is to validate the incoming request.
hemera.add(
{
topic: 'math',
cmd: 'add',
properties: {
a: { type: 'number' },
b: { type: 'number' }
}
},
(req, cb) => {
cb(null, req.a + req.b)
}
)
Response validation
You can also validate your response payload by using the schema
property where you can define request
and response
schemas. Response error isn't validated but must be from type Error
.
hemera.add(
{
topic: 'math',
cmd: 'add',
schema: {
response: {
type: 'number'
}
}
},
(req, cb) => {
cb(null, req.a + req.b)
}
)
Reuse schemas
You can reuse schemas across server actions. This functionality is provided by a custom schema store.
If you reference a schema with schema#
it will be replaced by the JSON schema at startup time.
hemera.addSchema({
$id: 'myRequestSchema',
type: 'object',
properties: {
a: { type: 'number' },
b: { type: 'number' }
}
})
hemera.addSchema({
$id: 'myResponseSchema',
type: 'number'
})
hemera.add(
{
topic: 'math',
cmd: 'add',
schema: {
request: 'myRequestSchema#',
response: 'myResponseSchema#'
}
},
(resp, cb) => {
cb()
}
)
Change Ajv settings
const hemera = new Hemera(nats)
hemera.use(
require('hemera-ajv', {
ajv: {
coerceTypes: true,
useDefaults: true,
removeAdditional: true
}
})
)
Plugin decorators
- .addSchema(Object schema)