@saxjst/koa-joi-validator

0.0.1 • Public • Published

Koa-Joi-Validator

Middleware validate a koa request using joi schemas

Build Status Coverage Status Maintainability tested with jest code style: prettier

Features

  • Allows schemas to validate themselves (no joi version dependencies)
  • Validate query, params, header and body with dedicated schemas

Usage

As global middleware

const Koa = require("koa");
const Joi = require("@hapi/joi");
const validator = require("koa-joi-validator");

const app = new Koa();

const schemas = {
  headers: {
    // Request headers Joi validation object
    "x-request-id": joi
      .string()
      .alphanum()
      .length(32)
  },
  query: {
    // URL query string Joi validation object
    userid: joi.string().required()
  },
  params: {
    // URL path parameters Joi validation object
  },
  body: {
    // POST body Joi validation object
  }
};

app.use(validate(schemas));

app.use(async ctx => {
  ctx.body = "Hello World";
});

app.listen(5000);

As router middleware

const validator = require("koa-joi-validator");
const router = new Router()

const schemas = {
  body: {
    username: Joi.string().required(),
    password: Joi.string().required()
  }
})

router.post('/login', validator(schemas), async ctx => {
  const { username, password } = ctx.body
  const response = await login(username, password)
  ctx.body = response
})

API

validator(schemas) ⇒ function

Generate a Koa middleware function to validate a request using the provided validation objects.

Returns: A validation middleware function.

Param Type Description
schemas Object
[schemas.headers] Object headers schema
[schemas.params] Object params schema
[schemas.query] Object query schema
[schemas.body] Object body schema

License

MIT © saxjst

Readme

Keywords

Package Sidebar

Install

npm i @saxjst/koa-joi-validator

Weekly Downloads

1

Version

0.0.1

License

MIT

Unpacked Size

9.44 kB

Total Files

7

Last publish

Collaborators

  • saxjst