hemera-ajv

1.0.2 • Public • Published

Hemera-ajv package

npm styled with prettier

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)

Package Sidebar

Install

npm i hemera-ajv

Weekly Downloads

2,138

Version

1.0.2

License

MIT

Unpacked Size

8.54 kB

Total Files

6

Last publish

Collaborators

  • starptech