hemera-joi

6.0.2 • Public • Published

Hemera-joi package

npm styled with prettier

This is a plugin to use Joi for request/response validation.

Usage

const hemera = new Hemera(nats)
hemera.use(require('hemera-joi'))

Request validation

The primary purpose of joi is to validate the incoming request. You can define your validation schema with the joi$ property or inline.

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)
  }
)

Response validation

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.

Missing fields

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.

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 })
  }
)

Joi settings

You can modify the joi validation settings with the pre and post plugin options.

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 }
  })
)

Base schemas

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.

hemera.use(HemeraJoi, {
  basePreSchema: {
    topic: Joi.string().required(),
    cmd: Joi.string().required()
  },
  basePostSchema: {
    userId: Joi.number().required()
  },
  pre: { allowUnknown: false }
})

Plugin decorators

  • .joi

Package Sidebar

Install

npm i hemera-joi

Weekly Downloads

630

Version

6.0.2

License

MIT

Unpacked Size

5.3 kB

Total Files

5

Last publish

Collaborators

  • starptech