Ready to take your JavaScript development to the next level? Meet npm Enterprise - the ultimate in enterprise JavaScript. Learn more »

hemera-ajv

1.0.0 • 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)

install

npm i hemera-ajv

Downloadsweekly downloads

18

version

1.0.0

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability