|
| 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 |
0 commit comments