4.1.0 • Published 4 years ago

koa-yup-validator v4.1.0

Weekly downloads
345
License
MIT
Repository
github
Last release
4 years ago

koa-yup-validator CircleCI Greenkeeper badge

Koa middleware for validating and coercing request data.

Usage

yarn add yup koa-yup-validator

import createValidator from "koa-yup-validator";
const validator = createValidator(validators, options); /* see below */

Arguments

validators

{
  body: schema; // validates request body
  headers: schema; // validates request headers
  params: schema; // validates path params
  query: schema; // validates query params
}

options:

Specify options for each validator ie.

{
  body: options
}
partialAllows data to satisfy schema partially at root level (if the data key exists it must satisfy schema). Useful for example patch operations.
yupOptions to be passed to yup validate.

Error handling

There is an optional error middleware you may use for handling errors thrown by the validation middleware:

import { createErrorMiddleware } from "koa-yup-validator";
app.use(createErrorMiddleware());
//...your routes

Examples

Validate headers and body

import * as yup from "yup";
import validator from "koa-yup-validator";

const Pizza = yup.object().shape({
  name: yup.string().required(),
  toppings: yup.array().of(yup.string()),
});
const RequiredHeaders = yup.object().shape({
  Authorization: yup.string().required(),
  "x-pizza-maker": yup.string(),
});

router.post(
  "/pizza",
  validator({ body: Pizza, headers: RequiredHeaders }),
  (ctx) => {
    console.log(ctx.request.headers["x-pizza-maker"]);
    ctx.response.status = 200;
    ctx.response.body = "Valid pizza!";
  }
);

// Pass yup options for body
router.post(
  "/strict-pizza",
  validator(
    { body: Pizza, headers: RequiredHeaders },
    { body: { yup: { strict: true } } }
  ),
  (ctx) => {
    console.log(ctx.request.headers["x-pizza-maker"]);
    ctx.response.status = 200;
    ctx.response.body = "Valid pizza!";
  }
);
4.1.0

4 years ago

4.0.1

4 years ago

4.0.0

4 years ago

3.0.0

5 years ago

2.0.0

5 years ago

1.0.7

5 years ago

1.0.7-1

5 years ago

1.0.7-0

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

7 years ago