# @readyplayerme/next-api-router

> Simple utility allowing to route API endpoints by http methods with middleware functionality.

Latest version **1.4.4** (published 2022-09-28) · ISC license · 0 weekly downloads

## Install

```sh
npm install @readyplayerme/next-api-router
pnpm add @readyplayerme/next-api-router
yarn add @readyplayerme/next-api-router
bun add @readyplayerme/next-api-router
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.4.4 |
| Published | 2022-09-28 |
| First published | 2021-09-23 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 6 |
| Unpacked size | 29.2 KB |
| Known vulnerabilities | 0 (+14 in 1 direct dependencies) |
| Install scripts | no |
| Author | Readyplayerme Team |
| Maintainers | bernhard-rpm, olafhaag, blanxiii, rafaelbeckel, wolf_dan, elar.rpm, sgt3v, harrison-wolf, yuri_wolf3d, ygrishajev.rpm, rainerw3d |

## Links

- npm: https://www.npmjs.com/package/@readyplayerme/next-api-router
- Repository: https://github.com/readyplayerme/next-api-router
- Homepage: https://github.com/readyplayerme/next-api-router#readme
- Issues: https://github.com/readyplayerme/next-api-router/issues
- npm.io page: https://npm.io/package/@readyplayerme/next-api-router

## Dependencies (6)

- [ajv](https://npm.io/package/ajv.md) ^8.6.3
- [next](https://npm.io/package/next.md) ^12.3.1
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [ajv-formats](https://npm.io/package/ajv-formats.md) ^2.1.1
- [http-assert](https://npm.io/package/http-assert.md) ^1.5.0
- [http-errors](https://npm.io/package/http-errors.md) ^1.8.0

## Recent versions

- 1.4.4 (latest) — 2022-09-28
- 1.4.3 — 2022-09-21
- 1.4.2 — 2022-05-24
- 1.4.1 — 2022-05-23
- 1.4.0 — 2022-05-23
- 1.3.7 — 2022-02-15
- 1.3.6 — 2021-12-16
- 1.2.4 — 2021-11-16
- 1.2.3 — 2021-11-16
- 1.2.2 — 2021-10-20
- 1.2.1 — 2021-10-20
- 1.2.0 — 2021-10-13
- 1.1.7 — 2021-10-07
- 1.1.6 — 2021-10-06
- 1.1.5 — 2021-10-06
- … 7 more at https://npm.io/package/@readyplayerme/next-api-router/versions

## README

# Next.js API router

Simple utility allowing to route API endpoints by http methods with middleware functionality.

## API

### NextApiRouter
* `#create()` - creates a NextApiRouter instance
### NextApiRouter.prototype
* `#setLogger(logger: Console): this` - sets a logger to be used by router. Default: `console`
* `#use(middleware): this` - adds a middleware to execution pipeline. Middleware is a function receiving arguments as follows:
  * `request: NextApiRequest` 
  * `response: NextApiResponse`
* `#post(handler)`/`#get(handler)`/`#put(handler)`/`#patch(handler)`/`#delete(handler)`/`#options()` - adds a handler to requests with respective method. Handlers return value is sent as a response with status 200 unless response is already sent explicitly using Nextjs API. Handler is a function receiving arguments as follows:
    * `request: NextApiRequest`
    * `response: NextApiResponse` 
* `#init()` - initializer returning a Nextjs API handler which should exported by default from a Nextjs route endpoint file
* `#events` - event emitter

### Handler
Route handler can be added as a function or a configuration object:

```typescript
export declare type NextApiRouterHandlerFn<T = any> = (
  this: NextApiRouterHandlerFnCtx,
  req: NextApiRequest,
  res: NextApiResponse<T>
) => T | Promise<T>;
```

or

```typescript
export interface NextApiConfigurableHandlerOptions {
  schema?: ValidationSchema;
  middlewares?: NextApiRouterHandlerFn[];
  handler: NextApiRouterHandlerFn | NextApiRouterHandlerFn[];
}
```

Schema is jsonschema validating request/response payloads. Validation is omitted if schema is not provided. It is responding with `400` if request payload is not valid and `500` for response.
```typescript
export interface ValidationSchema {
  query?: AnySchema;
  body?: AnySchema;
  response?: {
    [key: number]: AnySchema;
  };
}
```
It is possible to separately validate `query`, `body` and response payload by response code. E.g. the schema as follows is only validating response payloads with status `200`. This schema is filtering out fields that are not specified and tries to cast types.
```typescript
const schema = {
  response: {
    200: schema
  }
}
```

jsonschema is implemented using [ajv](https://ajv.js.org/) with [ajv-formats](https://www.npmjs.com/package/ajv-formats) included.

## Usage notes
* it is possible to add multiple middlewares which would be executed in order of addition
* handler is executed after a middleware
* middleware added before handler is ignored
* pipeline execution stops if middleware ends a request
* it is possible to subscribe to error events (e.g. for reporting/logging purposes)

## Example

```javascript
const router = NextApiRouter.create() // or new NextApiRouter()
    .use(function (request: NextApiRequest, response: NextApiResponse) { // Add a middleware
      this.user = { id: 1, name: 'John Doe'} // middlewares and handlers share common context
    })
    .post(function (request: NextApiRequest, response: NextApiResponse) {
      return this.user // respond with some payload
    })
    // this middleware is only added to a subsequent handerlr.
    // E.g. it is called before get handler below but not the post one above
    .use(middleware)
    .get(handler)

router.events.on("error", (error) => /* process error */)

export default router.init()
```

## Roadmap

* add endpoint generic typing for request

---
_Source: https://npm.io/package/@readyplayerme/next-api-router · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
