在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:Turee/koa-yup-validator开源软件地址:https://github.com/Turee/koa-yup-validator开源编程语言:TypeScript 97.8%开源软件介绍:koa-yup-validatorKoa middleware for validating and coercing request data. Usage
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.
Error handlingThere 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 ExamplesValidate 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!";
}
); |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论