Skip to content

WebForgeOSS/koa-joi-validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 © muceres

About

Koa payload validator middleware using joi

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published