Skip to content

Commit b99e199

Browse files
authored
Merge pull request #3 from codecoolture/add-headers
Add support to check the 'headers' property from the incoming request
2 parents a6931d9 + e3c8476 commit b99e199

3 files changed

Lines changed: 53 additions & 3 deletions

File tree

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- [`validate(schemas, handler)`](#validateschemas-handler)
2323
- [`schemas`](#schemas)
2424
- [`schemas.body`](#schemasbody)
25+
- [`schemas.headers`](#schemasheaders)
2526
- [`schemas.query`](#schemasquery)
2627
- [`handler`](#handler)
2728

@@ -126,7 +127,7 @@ export default withJoi({
126127

127128
### `validate(schemas, handler)`
128129

129-
The `validate` function has support to check two request's fields: `query` and `body`. The first argument for this function should always be an object with the desired validation schemas.
130+
The `validate` function has support to check the following request fields: `body`, `headers` and `query`. The first argument for this function should always be an object with the desired validation schemas.
130131

131132
#### `schemas`
132133

@@ -140,6 +141,16 @@ Even if empty, this argument is required.
140141

141142
A valid `joi` schema.
142143

144+
##### `schemas.headers`
145+
146+
**Optional**
147+
148+
> Note: since most of the time you may receive more headers than expected, it is a good practice to make this
149+
> schema always support [`unknown`](https://joi.dev/api/?v=17.3.0#objectunknownallow) keys. Otherwise, the validation
150+
> will always fail.
151+
152+
A valid `joi` schema.
153+
143154
##### `schemas.query`
144155

145156
**Optional**

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)