Skip to content

Commit f277b80

Browse files
committed
Public release 🚀
0 parents  commit f277b80

13 files changed

Lines changed: 8839 additions & 0 deletions

.eslintrc.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = {
2+
root: true,
3+
parser: "@typescript-eslint/parser",
4+
plugins: ["@typescript-eslint"],
5+
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
6+
};

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
dist
2+
node_modules
3+
yarn-error.log

.prettierrc.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
printWidth: 120,
3+
};

CONTRIBUTE.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# How to contribute to the project?
2+
3+
Since the project is quite small, let's try to keep things simple 🙂
4+
5+
- If there is bug or typo you would like to address, please go and open a Pull Request. As a general guideline, try to keep things consistent with the existing code.
6+
- For a feature request, [create a new issue](https://github.com/codecoolture/next-joi/issues/new/choose) so we can discuss its viability.

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2020 Sergio Álvarez-Suárez
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
<h1 align="center">
2+
next-joi
3+
</h1>
4+
5+
<p align="center">
6+
Validate NEXT.js API Routes with <em>joi</em> 😄
7+
</p>
8+
9+
- [Install](#install)
10+
- [Getting started](#getting-started)
11+
- [How does it work?](#how-does-it-work)
12+
- [Working with NEXT.js API Routes](#working-with-nextjs-api-routes)
13+
- [NEXT.js & `connect`-like middlewares](#nextjs--connect-like-middlewares)
14+
- [API](#api)
15+
- [`validate(schemas, handler)`](#validateschemas-handler)
16+
- [`schemas`](#schemas)
17+
- [`schemas.body`](#schemasbody)
18+
- [`schemas.query`](#schemasquery)
19+
- [`handler`](#handler)
20+
21+
## Install
22+
23+
```
24+
yarn add next-joi
25+
```
26+
27+
This package does not bundle with [`next.js`](https://github.com/vercel/next.js) or [`joi`](https://github.com/sideway/joi), so you will need to install them separately.
28+
29+
## Getting started
30+
31+
### How does it work?
32+
33+
The `validate` function will check the incoming request against the defined validation schemas. If the request does not comply with the schemas, it will be aborted inmediately and a `400 BAD REQUEST` response will be returned.
34+
35+
### Working with NEXT.js API Routes
36+
37+
If you are using standard NEXT.js API Routes, you may use the `validate` function to wrap your route definition and pass
38+
along the validation schema:
39+
40+
```ts
41+
import Joi from "joi";
42+
import validate from "next-joi";
43+
44+
const schema = Joi.object({
45+
birthdate: Joi.date().iso(),
46+
email: Joi.string().email().required(),
47+
name: Joi.string().required(),
48+
});
49+
50+
export default validate({ body: schema }, (req, res) => {
51+
// This function will be only executed if the incoming request complies
52+
// with the validation schema defined above.
53+
});
54+
```
55+
56+
### NEXT.js & `connect`-like middlewares
57+
58+
If your routes are powered by using a package such as `next-connect`, you can still use `validate`!
59+
The function is ready to work as a `connect` middleware just out-of-the-box:
60+
61+
```ts
62+
import Joi from "joi";
63+
import connect from "next-connect";
64+
import validate from "next-joi";
65+
66+
const schema = Joi.object({
67+
birthdate: Joi.date().iso(),
68+
email: Joi.string().email().required(),
69+
name: Joi.string().required(),
70+
});
71+
72+
export default connect().post(validate({ body: schema }), (req, res) => {
73+
// This function will be only executed if the incoming request complies
74+
// with the validation schema defined above.
75+
}))
76+
```
77+
78+
## API
79+
80+
### `validate(schemas, handler)`
81+
82+
The `validate` function has support to check two request's fields: `query` and `body`. Independently from the route's
83+
definition mechanism (see examples above), the first argument for this function should always be an object with the
84+
desired validation schemas.
85+
86+
#### `schemas`
87+
88+
**Required**
89+
90+
Even if empty, this argument is required.
91+
92+
##### `schemas.body`
93+
94+
**Optional**
95+
96+
A valid `joi` schema.
97+
98+
##### `schemas.query`
99+
100+
**Optional**
101+
102+
A valid `joi` schema.
103+
104+
#### `handler`
105+
106+
**Optional**
107+
108+
A valid `next` API Route handler. If you are using the `validate` function without a `connect`-like middleware engine, this argument becomes mandatory.
109+
110+
Example:
111+
112+
```ts
113+
const handler = function (req: NextApiRequest, res: NextApiResponse) {
114+
// implementation
115+
};
116+
117+
export default validate({}, handler);
118+
```

jest.config.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
};

package.json

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
{
2+
"name": "next-joi",
3+
"version": "1.0.0",
4+
"description": "Validate NEXT.js API Routes with joi",
5+
"keywords": [
6+
"nextjs",
7+
"joi",
8+
"middleware",
9+
"typescript"
10+
],
11+
"main": "dist/index.js",
12+
"types": "dist/index.d.ts",
13+
"files": [
14+
"dist/index.js",
15+
"dist/index.d.ts"
16+
],
17+
"author": {
18+
"email": "sergio@codecoolture.com",
19+
"name": "Codecoolture",
20+
"url": "https://codecoolture.com"
21+
},
22+
"license": "MIT",
23+
"bugs": {
24+
"url": "https://github.com/codecoolture/next-joi"
25+
},
26+
"homepage": "https://github.com/codecoolture/next-joi#readme",
27+
"repository": "https://github.com/codecoolture/next-joi",
28+
"peerDependencies": {
29+
"joi": "^17.1.1",
30+
"next": "^9.5.1"
31+
},
32+
"devDependencies": {
33+
"@types/jest": "^26.0.8",
34+
"@types/joi": "^14.3.4",
35+
"@types/test-listen": "^1.1.0",
36+
"@typescript-eslint/eslint-plugin": "^3.8.0",
37+
"@typescript-eslint/parser": "^3.8.0",
38+
"eslint": "^7.6.0",
39+
"eslint-config-prettier": "^6.11.0",
40+
"husky": "^4.2.5",
41+
"isomorphic-unfetch": "^3.0.0",
42+
"jest": "^26.2.2",
43+
"joi": "^17.1.1",
44+
"next": "^9.5.1",
45+
"next-connect": "^0.8.1",
46+
"prettier": "^2.0.5",
47+
"test-listen": "^1.1.0",
48+
"ts-jest": "^26.1.4",
49+
"typescript": "^3.9.7"
50+
},
51+
"scripts": {
52+
"prepublish": "yarn test && tsc",
53+
"test": "jest"
54+
},
55+
"husky": {
56+
"hooks": {
57+
"pre-push": "yarn test"
58+
}
59+
}
60+
}

src/index.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { Schema } from "joi";
2+
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
3+
import { RequestHandler, NextHandler } from "next-connect";
4+
5+
export type ValidableRequestFields = Pick<NextApiRequest, "query" | "body">;
6+
7+
export type ValidationSchemas = {
8+
[K in keyof ValidableRequestFields]?: Schema;
9+
};
10+
11+
export default function withJoi(schemas: ValidationSchemas): RequestHandler<NextApiRequest, NextApiResponse>;
12+
export default function withJoi(schemas: ValidationSchemas, handler: NextApiHandler): NextApiHandler;
13+
export default function withJoi(
14+
schemas: ValidationSchemas,
15+
handler?: NextApiHandler
16+
): NextApiHandler | RequestHandler<NextApiRequest, NextApiResponse> {
17+
return (req: NextApiRequest, res: NextApiResponse, next?: NextHandler) => {
18+
const fields: (keyof ValidableRequestFields)[] = ["body", "query"];
19+
20+
const hasValidationErrors = fields.some((field) => {
21+
const schema = schemas[field];
22+
23+
return schema && schema.required().validate(req[field]).error;
24+
});
25+
26+
if (hasValidationErrors) {
27+
return res.status(400).end();
28+
}
29+
30+
if (undefined !== next) {
31+
return next();
32+
}
33+
34+
if (undefined !== handler) {
35+
return handler(req, res);
36+
}
37+
38+
res.status(404).end();
39+
};
40+
}

0 commit comments

Comments
 (0)