Skip to content

Commit 3541581

Browse files
committed
docs: add README
1 parent 9a9cef6 commit 3541581

2 files changed

Lines changed: 88 additions & 1 deletion

File tree

README.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Next api interceptor
2+
3+
Interceptor for serverless nextjs api
4+
5+
## Install
6+
7+
using `npm`
8+
9+
```bash
10+
npm install @marcus-rise/next-api-interceptor
11+
```
12+
13+
or using `yarn`
14+
15+
```bash
16+
yarn add @marcus-rise/next-api-interceptor
17+
```
18+
19+
## Usage
20+
21+
You can create several interceptors and apply them in train
22+
23+
Interceptor is a wrapper function, that runs before a wrapped function
24+
25+
```tsx
26+
// src/interceptor/method-handlers.interceptor.ts
27+
import type {Interceptor} from "@marcus-rise/next-api-interceptor";
28+
import type {NextApiHandler} from "next";
29+
30+
enum RequestMethod {
31+
GET = "GET",
32+
POST = "POST",
33+
}
34+
35+
type MethodHandler<Handler extends NextApiHandler = NextApiHandler> = {
36+
method: RequestMethod | string;
37+
handler: Handler;
38+
};
39+
40+
const withMethodHandlers =
41+
(...allowedHandlers: Array<MethodHandler>): Interceptor =>
42+
(handler: NextApiHandler = () => {
43+
}) =>
44+
async (req, res) => {
45+
const allowedHandler = allowedHandlers.find((h) => h.method === req.method)?.handler;
46+
47+
if (!allowedHandler) {
48+
res.status(405).end();
49+
} else {
50+
await allowedHandler(req, res);
51+
}
52+
53+
return handler(req, res);
54+
};
55+
56+
export {withMethodHandlers};
57+
```
58+
59+
```ts
60+
// pages/api/test.ts
61+
import type {NextApiHandler} from "next";
62+
import {withMethodHandlers} from "../../src/interceptor/method-handlers.interceptor.ts";
63+
64+
const TestHandler: NextApiHandler = (req, response) => {
65+
return response.status(res.status).json({res: "hellow"});
66+
};
67+
68+
export default withMethodHandlers({
69+
method: "GET",
70+
handler: TestHandler,
71+
})();
72+
73+
// or
74+
75+
export default applyInterceptors(
76+
TestHandler,
77+
anotherInterceptor,
78+
withMethodHandlers({
79+
method: "GET",
80+
handler: TestHandler,
81+
}),
82+
yetAnotherOneInterceptor,
83+
);
84+
```
85+
86+
The execution order of example described above is: anotherInterceptor, withMethodHandlers,
87+
yetAnotherOneInterceptor, TestHandler

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "@marcus-rise/next-api-interceptor",
33
"version": "0.1.0",
44
"license": "MIT",
5-
"description": "nextjs api interceptor",
5+
"description": "Interceptor for serverless nextjs api",
66
"author": {
77
"name": "Ilya Konstantinov",
88
"email": "ilya.konstantinov2022@mail.ru",

0 commit comments

Comments
 (0)