Skip to content

Commit 554a5a9

Browse files
committed
Add support to validate req headers
1 parent a6931d9 commit 554a5a9

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

src/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { Schema } from "joi";
22
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
33
import { NextHandler, RequestHandler } from "next-connect";
44

5-
export type ValidableRequestFields = Pick<NextApiRequest, "query" | "body">;
5+
export type ValidableRequestFields = Pick<NextApiRequest, "body" | "headers" | "query">;
66

77
export type ValidationSchemas = {
88
[K in keyof ValidableRequestFields]?: Schema;
@@ -22,7 +22,7 @@ export default function withJoi(config?: Configuration): ValidationFunction {
2222

2323
return (schemas, handler) => {
2424
return (req: NextApiRequest, res: NextApiResponse, next?: NextHandler) => {
25-
const fields: (keyof ValidableRequestFields)[] = ["body", "query"];
25+
const fields: (keyof ValidableRequestFields)[] = ["body", "headers", "query"];
2626

2727
const hasValidationErrors = fields.some((field) => {
2828
const schema = schemas[field];

tests/index.spec.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,45 @@ function buildSuite({ handlerBuilder, title }: BuildSuiteOptions): void {
114114
});
115115
});
116116

117+
describe("handling headers validation", () => {
118+
const schema = Joi.object({
119+
"accept-language": Joi.string().valid("en", "es").required(),
120+
});
121+
122+
it("returns a 400 by default if unknown headers are not ignored", async () => {
123+
const handler = handlerBuilder(validate, { headers: schema }, postANewUser);
124+
125+
const response = await server.inject(handler, {
126+
headers: { "accept-language": "en" },
127+
method: "post",
128+
});
129+
130+
expect(response.status).toBe(400);
131+
});
132+
133+
it("returns a 200 response if the validation passes", async () => {
134+
const handler = handlerBuilder(validate, { headers: schema.unknown() }, postANewUser);
135+
136+
const response = await server.inject(handler, {
137+
headers: { "accept-language": "en" },
138+
method: "post",
139+
});
140+
141+
expect(response.status).toBe(200);
142+
});
143+
144+
it("returns a 400 response if the validation doesn't pass", async () => {
145+
const handler = handlerBuilder(validate, { headers: schema.unknown() }, postANewUser);
146+
147+
const response = await server.inject(handler, {
148+
headers: { "accept-language": "pt" },
149+
method: "post",
150+
});
151+
152+
expect(response.status).toBe(400);
153+
});
154+
});
155+
117156
describe("working with custom error handling", () => {
118157
const body = Joi.object({ name: Joi.string().required() });
119158

0 commit comments

Comments
 (0)