Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/berstend/tiny-request-router

:rocket: Fast, generic and type safe router (match request method and path).
https://github.com/berstend/tiny-request-router

cloudflare-workers request router typescript

Last synced: 13 days ago
JSON representation

:rocket: Fast, generic and type safe router (match request method and path).

Awesome Lists containing this project

README

        

# tiny-request-router [![ ](https://travis-ci.org/berstend/tiny-request-router.svg?branch=master)](https://travis-ci.org/berstend/tiny-request-router) [![ ](https://img.shields.io/npm/v/tiny-request-router.svg)](https://www.npmjs.com/package/tiny-request-router)

> Fast, generic and type safe router (match request method and path).

## Features

- Minimal and opinionless router, can be used in any script and environment.
- Matches a request method (e.g. `GET`) and a path (e.g. `/foobar`) against a list of routes
- Uses [path-to-regexp](https://github.com/pillarjs/path-to-regexp), which is used by express and therefore familiar
- Allows wildcards (e.g. `/user/(.*)/age`) and named parameters (e.g. `/info/:username/:age`)
- Will not call your handlers automatically, as it only cares about matching
- Battle hardened in production ([Cloudflare Worker](https://www.cloudflare.com/products/cloudflare-workers/) with 10M requests per day)
- No magic, no assumptions, no fluff, type safe, tested

### Route testing

- You can use the [Express Route Tester](https://forbeslindesay.github.io/express-route-tester/) (select `2.0.0`) to debug your path patterns quickly

## Installation

```bash
yarn add tiny-request-router
# or
npm install --save tiny-request-router
```

## Usage (JavaScript/TypeScript)

```typescript
import { Router } from 'tiny-request-router'
// NodeJS: const { Router } = require('tiny-request-router')

const router = new Router()

router
.get('/(v1|v2)/:name/:age', 'foo1')
.get('/info/(.*)/export', 'foo2')
.post('/upload/user', 'foo3')

const match1 = router.match('GET', '/v1/')
// => null

const match2 = router.match('GET', '/v1/bob/22')
// => { handler: 'foo1', params: { name: 'bob', age: '22' }, ... }
```

### Make your handlers type safe (TypeScript)

```typescript
import { Router, Method, Params } from 'tiny-request-router'

// Let the router know that handlers are async functions returning a Response
type Handler = (params: Params) => Promise

const router = new Router()
router.all('*', async () => new Response('Hello'))

const match = router.match('GET' as Method, '/foobar')
if (match) {
// Call the async function of that match
const response = await match.handler()
console.log(response) // => Response('Hello')
}
```

## Example: Cloudflare Workers (JavaScript)

_Use something like [wrangler](https://github.com/cloudflare/wrangler) to bundle the router with your worker code._

```js
import { Router } from 'tiny-request-router'

const router = new Router()
router.get('/worker', async () => new Response('Hi from worker!'))
router.get('/hello/:name', async params => new Response(`Hello ${params.name}!`))
router.post('/test', async () => new Response('Post received!'))

// Main entry point in workers
addEventListener('fetch', event => {
const request = event.request
const { pathname } = new URL(request.url)

const match = router.match(request.method, pathname)
if (match) {
event.respondWith(match.handler(match.params))
}
})
```

---

## API

#### Table of Contents

- [Method()](#method)
- [RouteOptions()](#routeoptions)
- [RouteMatch()](#routematch)
- [class: Router](#class-router)
- [.routes](#routes)
- [.all(path, handler, options)](#allpath-handler-options)
- [.get(path, handler, options)](#getpath-handler-options)
- [.post(path, handler, options)](#postpath-handler-options)
- [.put(path, handler, options)](#putpath-handler-options)
- [.patch(path, handler, options)](#patchpath-handler-options)
- [.delete(path, handler, options)](#deletepath-handler-options)
- [.head(path, handler, options)](#headpath-handler-options)
- [.options(path, handler, options)](#optionspath-handler-options)
- [.match(method, path)](#matchmethod-path)

### [Method()](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L6-L6)

Type: **(`"GET"` \| `"POST"` \| `"PUT"` \| `"PATCH"` \| `"DELETE"` \| `"HEAD"` \| `"OPTIONS"`)**

Valid HTTP methods for matching.

---

### [RouteOptions()](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L39-L39)

**Extends: TokensToRegexpOptions**

Optional route options.

Example:

```javascript
// When `true` the regexp will be case sensitive. (default: `false`)
sensitive?: boolean;

// When `true` the regexp allows an optional trailing delimiter to match. (default: `false`)
strict?: boolean;

// When `true` the regexp will match to the end of the string. (default: `true`)
end?: boolean;

// When `true` the regexp will match from the beginning of the string. (default: `true`)
start?: boolean;

// Sets the final character for non-ending optimistic matches. (default: `/`)
delimiter?: string;

// List of characters that can also be "end" characters.
endsWith?: string;

// Encode path tokens for use in the `RegExp`.
encode?: (value: string) => string;
```

---

### [RouteMatch()](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L67-L70)

**Extends: Route<HandlerType>**

The object returned when a route matches.

The handler can then be used to execute the relevant function.

Example:

```javascript
{
params: Params
matches?: RegExpExecArray
method: Method | MethodWildcard
path: string
regexp: RegExp
options: RouteOptions
keys: Keys
handler: HandlerType
}
```

---

### class: [Router](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L86-L168)

Tiny request router. Allows overloading of handler type to be fully type safe.

Example:

```javascript
import { Router, Method, Params } from 'tiny-request-router'

// Let the router know that handlers are async functions returning a Response
type Handler = (params: Params) => Promise

const router = new Router()
```

---

#### .[routes](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L88-L88)

List of all registered routes.

---

#### .[all(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L91-L93)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches any method.

---

#### .[get(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L95-L97)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the GET method.

---

#### .[post(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L99-L101)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the POST method.

---

#### .[put(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L103-L105)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the PUT method.

---

#### .[patch(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L107-L109)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the PATCH method.

---

#### .[delete(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L111-L113)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the DELETE method.

---

#### .[head(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L115-L117)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the HEAD method.

---

#### .[options(path, handler, options)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L119-L121)

- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `handler` **HandlerType**
- `options` **[RouteOptions](#routeoptions)** (optional, default `{}`)

Add a route that matches the OPTIONS method.

---

#### .[match(method, path)](https://github.com/berstend/tiny-request-router/blob/5e7d69be1e37a6d2d14c611efe77ba2ef6ea9f83/src/router.ts#L135-L152)

- `method` **[Method](#method)**
- `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**

Returns: **([RouteMatch](#routematch)<HandlerType> | null)**

Match the provided method and path against the list of registered routes.

Example:

```javascript
router.get('/foobar', async () => new Response('Hello'))

const match = router.match('GET', '/foobar')
if (match) {
// Call the async function of that match
const response = await match.handler()
console.log(response) // => Response('Hello')
}
```

---

## More info

Please check out the [tiny source code](src/router.ts) or [tests](test/functionality.ts) for more info.

## License

MIT