Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
2529e5ce24
|
|||
|
42de017ba0
|
|||
|
81dd03af27
|
|||
|
7fe0a5405f
|
|||
|
|
05984eb7da | ||
|
|
ba371dcc6d | ||
|
|
aeb4eb06e4 | ||
|
efd74609f1
|
|||
|
|
fbc862a1f0 | ||
|
01487748af
|
|||
|
|
3374b92075
|
||
|
e8212b5fa8
|
|||
|
|
ded6b81e28 | ||
|
|
972dc916f7 | ||
|
d3b86f1dbe
|
|||
|
aadb398b48
|
|||
|
5fa3475a20
|
|||
|
0637549e90
|
|||
|
f3279e71fc
|
|||
|
bdb7be3699
|
|||
|
45a781ea66
|
|||
|
7f44f304a2
|
|||
|
a786262ec6
|
|||
|
8e58dc349e
|
|||
|
e94e84a742
|
|||
|
b16a56bbca
|
246
README.md
246
README.md
@@ -1,6 +1,6 @@
|
|||||||
# Cloudflare Workers Router
|
# Cloudflare Workers Router
|
||||||
|
|
||||||
Cloudflare Workers Router is a super lightweight router (2.30 KiB) with middleware support and **ZERO dependencies** for [Cloudflare Workers](https://workers.cloudflare.com/).
|
Cloudflare Workers Router is a super lightweight router (1.3K gzipped) with middleware support and **ZERO dependencies** for [Cloudflare Workers](https://workers.cloudflare.com/).
|
||||||
|
|
||||||
When I was trying out Cloudflare Workers I almost immediately noticed how fast it was compared to other serverless offerings. So I wanted to build a full-fledged API to see how it performs doing real work, but since I wasn't able to find a router that suited my needs I created my own.
|
When I was trying out Cloudflare Workers I almost immediately noticed how fast it was compared to other serverless offerings. So I wanted to build a full-fledged API to see how it performs doing real work, but since I wasn't able to find a router that suited my needs I created my own.
|
||||||
|
|
||||||
@@ -9,82 +9,175 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
|||||||
|
|
||||||
## Contents
|
## Contents
|
||||||
|
|
||||||
|
- [Features](#features)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
- [Reference](#reference)
|
- [Reference](#reference)
|
||||||
- [Setup](#setup)
|
- [Setup](#setup)
|
||||||
|
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- ZERO dependencies
|
||||||
|
- Lightweight (1.3K gzipped)
|
||||||
|
- Fully written in TypeScript
|
||||||
|
- Integrated Debug-Mode & CORS helper
|
||||||
|
- Built specifically around Middlewares
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Simple Example
|
### TypeScript Example
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
|
export interface Env {
|
||||||
|
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
|
||||||
|
// MY_KV_NAMESPACE: KVNamespace
|
||||||
|
//
|
||||||
|
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
|
||||||
|
// MY_DURABLE_OBJECT: DurableObjectNamespace
|
||||||
|
//
|
||||||
|
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
|
||||||
|
// MY_BUCKET: R2Bucket
|
||||||
|
}
|
||||||
|
|
||||||
```javascript
|
|
||||||
import Router from '@tsndr/cloudflare-worker-router'
|
|
||||||
|
|
||||||
// Initialize router
|
// Initialize router
|
||||||
const router = new Router()
|
const router = new Router<Env>()
|
||||||
|
|
||||||
// Enabling buildin CORS support
|
// Enabling build in CORS support
|
||||||
router.cors()
|
router.cors()
|
||||||
|
|
||||||
// Register global middleware
|
// Register global middleware
|
||||||
router.use(({ req, res, next }) => {
|
router.use(({ req, res, next }) => {
|
||||||
res.headers.set('X-Global-Middlewares', 'true')
|
res.headers.set('X-Global-Middlewares', 'true')
|
||||||
next()
|
next()
|
||||||
})
|
})
|
||||||
|
|
||||||
// Simple get
|
// Simple get
|
||||||
router.get('/user', ({ req, res }) => {
|
router.get('/user', ({ req, res }) => {
|
||||||
res.body = {
|
res.body = {
|
||||||
data: {
|
data: {
|
||||||
id: 1,
|
id: 1,
|
||||||
name: 'John Doe'
|
name: 'John Doe'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Post route with url parameter
|
// Post route with url parameter
|
||||||
router.post('/user/:id', ({ req, res }) => {
|
router.post('/user/:id', ({ req, res }) => {
|
||||||
|
|
||||||
const userId = req.params.id
|
const userId = req.params.id
|
||||||
|
|
||||||
// Do stuff...
|
// Do stuff...
|
||||||
|
|
||||||
if (errorDoingStuff) {
|
if (errorDoingStuff) {
|
||||||
res.status = 400
|
res.status = 400
|
||||||
res.body = {
|
res.body = {
|
||||||
error: 'User did stupid stuff!'
|
error: 'User did stupid stuff!'
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status = 204
|
res.status = 204
|
||||||
})
|
})
|
||||||
|
|
||||||
// Delete route using a middleware
|
// Delete route using a middleware
|
||||||
router.delete('/user/:id', ({ req, res, next }) => {
|
router.delete('/user/:id', ({ req, res, next }) => {
|
||||||
|
|
||||||
if (!apiTokenIsCorrect) {
|
if (!apiTokenIsCorrect) {
|
||||||
res.status = 401
|
res.status = 401
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await next()
|
await next()
|
||||||
}, (req, res) => {
|
}, (req, res) => {
|
||||||
|
|
||||||
const userId = req.params.id
|
const userId = req.params.id
|
||||||
|
|
||||||
// Do stuff...
|
// Do stuff...
|
||||||
})
|
})
|
||||||
|
|
||||||
// Listen Cloudflare Workers Fetch Event
|
// Listen Cloudflare Workers Fetch Event
|
||||||
export default {
|
export default {
|
||||||
async fetch(request, env) {
|
async fetch(request: Request, env: Env): Promise<Response> {
|
||||||
return router.handle(env, request)
|
return router.handle(env, request)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>JavaScript Example</summary>
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
|
// Initialize router
|
||||||
|
const router = new Router()
|
||||||
|
|
||||||
|
// Enabling build in CORS support
|
||||||
|
router.cors()
|
||||||
|
|
||||||
|
// Register global middleware
|
||||||
|
router.use(({ req, res, next }) => {
|
||||||
|
res.headers.set('X-Global-Middlewares', 'true')
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Simple get
|
||||||
|
router.get('/user', ({ req, res }) => {
|
||||||
|
res.body = {
|
||||||
|
data: {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Post route with url parameter
|
||||||
|
router.post('/user/:id', ({ req, res }) => {
|
||||||
|
|
||||||
|
const userId = req.params.id
|
||||||
|
|
||||||
|
// Do stuff...
|
||||||
|
|
||||||
|
if (errorDoingStuff) {
|
||||||
|
res.status = 400
|
||||||
|
res.body = {
|
||||||
|
error: 'User did stupid stuff!'
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status = 204
|
||||||
|
})
|
||||||
|
|
||||||
|
// Delete route using a middleware
|
||||||
|
router.delete('/user/:id', ({ req, res, next }) => {
|
||||||
|
|
||||||
|
if (!apiTokenIsCorrect) {
|
||||||
|
res.status = 401
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await next()
|
||||||
|
}, (req, res) => {
|
||||||
|
|
||||||
|
const userId = req.params.id
|
||||||
|
|
||||||
|
// Do stuff...
|
||||||
|
})
|
||||||
|
|
||||||
|
// Listen Cloudflare Workers Fetch Event
|
||||||
|
export default {
|
||||||
|
async fetch(request, env) {
|
||||||
|
return router.handle(env, request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
@@ -96,6 +189,10 @@ Enable or disable debug mode. Which will return the `error.stack` in case of an
|
|||||||
#### `state`
|
#### `state`
|
||||||
State is a `boolean` which determines if debug mode should be enabled or not (default: `true`)
|
State is a `boolean` which determines if debug mode should be enabled or not (default: `true`)
|
||||||
|
|
||||||
|
Key | Type | Default Value
|
||||||
|
---------------------- | --------- | -------------
|
||||||
|
`state` | `boolean` | `true`
|
||||||
|
|
||||||
|
|
||||||
### `router.use([...handlers])`
|
### `router.use([...handlers])`
|
||||||
|
|
||||||
@@ -106,7 +203,9 @@ Register a global middleware handler.
|
|||||||
|
|
||||||
Handler is a `function` which will be called for every request.
|
Handler is a `function` which will be called for every request.
|
||||||
|
|
||||||
|
|
||||||
#### `ctx`
|
#### `ctx`
|
||||||
|
|
||||||
Object containing `env`, [`req`](#req-object), [`res`](#res-object), `next`
|
Object containing `env`, [`req`](#req-object), [`res`](#res-object), `next`
|
||||||
|
|
||||||
|
|
||||||
@@ -126,16 +225,19 @@ Key | Type | Default Value
|
|||||||
`optionsSuccessStatus` | `integer` | `204`
|
`optionsSuccessStatus` | `integer` | `204`
|
||||||
|
|
||||||
|
|
||||||
### `router.any(url, [...handlers])`
|
### Supported Methods
|
||||||
### `router.connect(url, [...handlers])`
|
|
||||||
### `router.delete(url, [...handlers])`
|
- `router.any(url, [...handlers])`
|
||||||
### `router.get(url, [...handlers])`
|
- `router.connect(url, [...handlers])`
|
||||||
### `router.head(url, [...handlers])`
|
- `router.delete(url, [...handlers])`
|
||||||
### `router.options(url, [...handlers])`
|
- `router.get(url, [...handlers])`
|
||||||
### `router.patch(url, [...handlers])`
|
- `router.head(url, [...handlers])`
|
||||||
### `router.post(url, [...handlers])`
|
- `router.options(url, [...handlers])`
|
||||||
### `router.put(url, [...handlers])`
|
- `router.patch(url, [...handlers])`
|
||||||
### `router.trace(url, [...handlers])`
|
- `router.post(url, [...handlers])`
|
||||||
|
- `router.put(url, [...handlers])`
|
||||||
|
- `router.trace(url, [...handlers])`
|
||||||
|
|
||||||
|
|
||||||
#### `url` (string)
|
#### `url` (string)
|
||||||
|
|
||||||
@@ -180,46 +282,55 @@ Key | Type | Description
|
|||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
---
|
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
|
||||||
### ❗️ Compatibility ❗️
|
|
||||||
|
|
||||||
CLI Tool | Router
|
|
||||||
-------- | ------
|
|
||||||
[wrangler2](https://github.com/cloudflare/wrangler2#readme) | Use `v2.x.x` or later.
|
|
||||||
[@cloudflare/wrangler](https://github.com/cloudflare/wrangler#readme) | Use `v1.x.x`, [here](https://github.com/tsndr/cloudflare-worker-router/tree/legacy#readme).
|
|
||||||
|
|
||||||
See [Migration from v1.x.x to v2.x.x](https://github.com/tsndr/cloudflare-worker-router/blob/main/MIGRATION.md#migration-guide) if you want to update.
|
#### Initialize Project
|
||||||
|
|
||||||
---
|
```bash
|
||||||
|
wrangler init <name>
|
||||||
|
```
|
||||||
|
|
||||||
### **[Wrangler2](https://github.com/cloudflare/wrangler2#readme)**
|
Use of TypeScript is strongly encouraged :)
|
||||||
|
|
||||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/), then install the router using this command
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i -D @tsndr/cloudflare-worker-router
|
npm i -D @tsndr/cloudflare-worker-router
|
||||||
```
|
```
|
||||||
|
|
||||||
and replace your `index.ts` / `index.js` with one of the following scripts
|
|
||||||
|
|
||||||
<details>
|
### TypeScript (<code>src/index.ts</code>)
|
||||||
<summary>TypeScript (<code>src/index.ts</code>)</summary>
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import Router from '@tsndr/cloudflare-worker-router'
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
export interface Env {
|
export interface Env {
|
||||||
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
|
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
|
||||||
// MY_KV_NAMESPACE: KVNamespace;
|
// MY_KV_NAMESPACE: KVNamespace
|
||||||
//
|
//
|
||||||
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
|
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
|
||||||
// MY_DURABLE_OBJECT: DurableObjectNamespace;
|
// MY_DURABLE_OBJECT: DurableObjectNamespace
|
||||||
//
|
//
|
||||||
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
|
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
|
||||||
// MY_BUCKET: R2Bucket;
|
// MY_BUCKET: R2Bucket
|
||||||
}
|
}
|
||||||
|
|
||||||
const router = new Router()
|
const router = new Router<Env>()
|
||||||
|
|
||||||
|
/// Example Route
|
||||||
|
//
|
||||||
|
// router.get(/'hi', ({ res }) => {
|
||||||
|
// res.body = 'Hello World'
|
||||||
|
//}
|
||||||
|
|
||||||
|
|
||||||
|
/// Example Route for splitting into multiple files
|
||||||
|
//
|
||||||
|
// const hiHandler: RouteHandler<Env> = ({ res }) => {
|
||||||
|
// res.body = 'Hello World'
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// router.get('/hi', hiHandler)
|
||||||
|
|
||||||
|
|
||||||
// TODO: add your routes here
|
// TODO: add your routes here
|
||||||
|
|
||||||
@@ -229,16 +340,22 @@ export default {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
</details>
|
|
||||||
|
|
||||||
|
### JavaScript (<code>src/index.js</code>)
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>JavaScript (<code>src/index.js</code>)</summary>
|
<summary>Consider using TypeScript instead :)</summary>
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
import Router from '@tsndr/cloudflare-worker-router'
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
const router = new Router()
|
const router = new Router()
|
||||||
|
|
||||||
|
// router.get(/'hi', ({ res }) => {
|
||||||
|
// res.body = 'Hello World'
|
||||||
|
//}
|
||||||
|
|
||||||
// TODO: add your routes here
|
// TODO: add your routes here
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
@@ -247,4 +364,3 @@ export default {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
</details>
|
|
||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "2.0.2",
|
"version": "2.3.0",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "2.0.2",
|
"version": "2.3.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^3.13.0",
|
"@cloudflare/workers-types": "^3.13.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "2.0.2",
|
"version": "2.3.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
|
|||||||
167
src/index.ts
167
src/index.ts
@@ -6,23 +6,23 @@
|
|||||||
* @property {string} url URL String
|
* @property {string} url URL String
|
||||||
* @property {RouterHandler[]} handlers Array of handler functions
|
* @property {RouterHandler[]} handlers Array of handler functions
|
||||||
*/
|
*/
|
||||||
export interface Route {
|
export interface Route<TEnv> {
|
||||||
method: string
|
method: string
|
||||||
url: string
|
url: string
|
||||||
handlers: RouterHandler[]
|
handlers: RouterHandler<TEnv>[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Context
|
* Router Context
|
||||||
*
|
*
|
||||||
* @typedef RouterContext
|
* @typedef RouterContext
|
||||||
* @property {Object<string, string>} env Environment
|
* @property {RouterEnv} env Environment
|
||||||
* @property {RouterRequest} req Request Object
|
* @property {RouterRequest} req Request Object
|
||||||
* @property {RouterResponse} res Response Object
|
* @property {RouterResponse} res Response Object
|
||||||
* @property {RouterNext} next Next Handler
|
* @property {RouterNext} next Next Handler
|
||||||
*/
|
*/
|
||||||
export interface RouterContext {
|
export interface RouterContext<TEnv> {
|
||||||
env: any
|
env: TEnv
|
||||||
req: RouterRequest
|
req: RouterRequest
|
||||||
res: RouterResponse
|
res: RouterResponse
|
||||||
next: RouterNext
|
next: RouterNext
|
||||||
@@ -37,7 +37,7 @@ export interface RouterContext {
|
|||||||
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
||||||
* @property {RouterRequestQuery} query Object containing all query parameters
|
* @property {RouterRequestQuery} query Object containing all query parameters
|
||||||
* @property {Headers} headers Request headers object
|
* @property {Headers} headers Request headers object
|
||||||
* @property {any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
|
* @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
|
||||||
* @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
|
* @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
|
||||||
*/
|
*/
|
||||||
export interface RouterRequest {
|
export interface RouterRequest {
|
||||||
@@ -46,7 +46,7 @@ export interface RouterRequest {
|
|||||||
params: RouterRequestParams
|
params: RouterRequestParams
|
||||||
query: RouterRequestQuery
|
query: RouterRequestQuery
|
||||||
headers: Headers
|
headers: Headers
|
||||||
body: any
|
body: string | any
|
||||||
cf?: IncomingRequestCfProperties
|
cf?: IncomingRequestCfProperties
|
||||||
[key: string]: any
|
[key: string]: any
|
||||||
}
|
}
|
||||||
@@ -75,13 +75,13 @@ export interface RouterRequestQuery {
|
|||||||
* @typedef RouterResponse
|
* @typedef RouterResponse
|
||||||
* @property {Headers} headers Response headers object
|
* @property {Headers} headers Response headers object
|
||||||
* @property {number} [status=204] Return status code (default: `204`)
|
* @property {number} [status=204] Return status code (default: `204`)
|
||||||
* @property {any} [body] Either an `object` (will be converted to JSON) or a string
|
* @property {string | any} [body] Either an `object` (will be converted to JSON) or a string
|
||||||
* @property {Response} [raw] A response object that is to be returned, this will void all other res properties and return this as is.
|
* @property {Response} [raw] A response object that is to be returned, this will void all other res properties and return this as is.
|
||||||
*/
|
*/
|
||||||
export interface RouterResponse {
|
export interface RouterResponse {
|
||||||
headers: Headers
|
headers: Headers
|
||||||
status?: number
|
status?: number
|
||||||
body?: any
|
body?: string | any
|
||||||
raw?: Response,
|
raw?: Response,
|
||||||
webSocket?: WebSocket
|
webSocket?: WebSocket
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ export interface RouterResponse {
|
|||||||
* Next Function
|
* Next Function
|
||||||
*
|
*
|
||||||
* @callback RouterNext
|
* @callback RouterNext
|
||||||
* @returns {Promise}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export interface RouterNext {
|
export interface RouterNext {
|
||||||
(): Promise<void>
|
(): Promise<void>
|
||||||
@@ -103,8 +103,8 @@ export interface RouterNext {
|
|||||||
* @param {RouterContext} ctx
|
* @param {RouterContext} ctx
|
||||||
* @returns {Promise<void> | void}
|
* @returns {Promise<void> | void}
|
||||||
*/
|
*/
|
||||||
export interface RouterHandler {
|
export interface RouterHandler<TEnv = any> {
|
||||||
(ctx: RouterContext): Promise<void> | void
|
(ctx: RouterContext<TEnv>): Promise<void> | void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -118,11 +118,11 @@ export interface RouterHandler {
|
|||||||
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||||
*/
|
*/
|
||||||
export interface RouterCorsConfig {
|
export interface RouterCorsConfig {
|
||||||
allowOrigin: string
|
allowOrigin?: string
|
||||||
allowMethods: string
|
allowMethods?: string
|
||||||
allowHeaders: string
|
allowHeaders?: string
|
||||||
maxAge: number
|
maxAge?: number
|
||||||
optionsSuccessStatus: number
|
optionsSuccessStatus?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -131,7 +131,7 @@ export interface RouterCorsConfig {
|
|||||||
* @public
|
* @public
|
||||||
* @class
|
* @class
|
||||||
*/
|
*/
|
||||||
export default class Router {
|
export class Router<TEnv = any> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Array
|
* Router Array
|
||||||
@@ -139,12 +139,15 @@ export default class Router {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {Route[]}
|
* @type {Route[]}
|
||||||
*/
|
*/
|
||||||
protected routes: Route[] = []
|
protected routes: Route<TEnv>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global Handlers
|
* Global Handlers
|
||||||
|
*
|
||||||
|
* @protected
|
||||||
|
* @type {RouterHandler[]}
|
||||||
*/
|
*/
|
||||||
protected globalHandlers: RouterHandler[] = []
|
protected globalHandlers: RouterHandler<TEnv>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Debug Mode
|
* Debug Mode
|
||||||
@@ -160,13 +163,15 @@ export default class Router {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {RouterCorsConfig}
|
* @type {RouterCorsConfig}
|
||||||
*/
|
*/
|
||||||
protected corsConfig: RouterCorsConfig = {
|
protected corsConfig: RouterCorsConfig = {}
|
||||||
allowOrigin: '*',
|
|
||||||
allowMethods: '*',
|
/**
|
||||||
allowHeaders: '*',
|
* CORS enabled
|
||||||
maxAge: 86400,
|
*-
|
||||||
optionsSuccessStatus: 204
|
* @protected
|
||||||
}
|
* @type {boolean}
|
||||||
|
*/
|
||||||
|
protected corsEnabled: boolean = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register global handlers
|
* Register global handlers
|
||||||
@@ -174,7 +179,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public use(...handlers: RouterHandler[]): Router {
|
public use(...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
for (let handler of handlers) {
|
for (let handler of handlers) {
|
||||||
this.globalHandlers.push(handler)
|
this.globalHandlers.push(handler)
|
||||||
}
|
}
|
||||||
@@ -188,7 +193,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public connect(url: string, ...handlers: RouterHandler[]): Router {
|
public connect(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('CONNECT', url, handlers)
|
return this.register('CONNECT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +204,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public delete(url: string, ...handlers: RouterHandler[]): Router {
|
public delete(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('DELETE', url, handlers)
|
return this.register('DELETE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,7 +215,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public get(url: string, ...handlers: RouterHandler[]): Router {
|
public get(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('GET', url, handlers)
|
return this.register('GET', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +226,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public head(url: string, ...handlers: RouterHandler[]): Router {
|
public head(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('HEAD', url, handlers)
|
return this.register('HEAD', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,7 +237,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public options(url: string, ...handlers: RouterHandler[]): Router {
|
public options(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('OPTIONS', url, handlers)
|
return this.register('OPTIONS', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,7 +248,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public patch(url: string, ...handlers: RouterHandler[]): Router {
|
public patch(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('PATCH', url, handlers)
|
return this.register('PATCH', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +259,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public post(url: string, ...handlers: RouterHandler[]): Router {
|
public post(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('POST', url, handlers)
|
return this.register('POST', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,7 +270,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public put(url: string, ...handlers: RouterHandler[]): Router {
|
public put(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('PUT', url, handlers)
|
return this.register('PUT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,7 +281,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public trace(url: string, ...handlers: RouterHandler[]): Router {
|
public trace(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('TRACE', url, handlers)
|
return this.register('TRACE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,7 +292,7 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public any(url: string, ...handlers: RouterHandler[]): Router {
|
public any(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('*', url, handlers)
|
return this.register('*', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,7 +302,7 @@ export default class Router {
|
|||||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public debug(state = true): Router {
|
public debug(state: boolean = true): Router<TEnv> {
|
||||||
this.debugMode = state
|
this.debugMode = state
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
@@ -308,11 +313,12 @@ export default class Router {
|
|||||||
* @param {RouterCorsConfig} [config]
|
* @param {RouterCorsConfig} [config]
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public cors(config?: RouterCorsConfig): Router {
|
public cors(config?: RouterCorsConfig): Router<TEnv> {
|
||||||
|
this.corsEnabled = true
|
||||||
this.corsConfig = {
|
this.corsConfig = {
|
||||||
allowOrigin: config?.allowOrigin || '*',
|
allowOrigin: config?.allowOrigin || '*',
|
||||||
allowMethods: config?.allowMethods || '*',
|
allowMethods: config?.allowMethods || '*',
|
||||||
allowHeaders: config?.allowHeaders || '*, Authorization',
|
allowHeaders: config?.allowHeaders || '*',
|
||||||
maxAge: config?.maxAge || 86400,
|
maxAge: config?.maxAge || 86400,
|
||||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||||
}
|
}
|
||||||
@@ -328,12 +334,13 @@ export default class Router {
|
|||||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
private register(method: string, url: string, handlers: RouterHandler[]): Router {
|
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
this.routes.push({
|
this.routes.push({
|
||||||
method,
|
method,
|
||||||
url,
|
url,
|
||||||
handlers
|
handlers
|
||||||
})
|
})
|
||||||
|
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,29 +348,39 @@ export default class Router {
|
|||||||
* Get Route by request
|
* Get Route by request
|
||||||
*
|
*
|
||||||
* @private
|
* @private
|
||||||
* @param {Request} request
|
* @param {RouterRequest} request
|
||||||
* @returns {RouterRequest | undefined}
|
* @returns {Route | undefined}
|
||||||
*/
|
*/
|
||||||
private getRoute(request: RouterRequest): Route | undefined {
|
private getRoute(request: RouterRequest): Route<TEnv> | undefined {
|
||||||
const url = new URL(request.url)
|
const url = new URL(request.url)
|
||||||
const pathArr = url.pathname.split('/').filter(i => i)
|
const pathArr = url.pathname.split('/').filter(i => i)
|
||||||
|
|
||||||
return this.routes.find(r => {
|
return this.routes.find(r => {
|
||||||
const routeArr = r.url.split('/').filter(i => i)
|
const routeArr = r.url.split('/').filter(i => i)
|
||||||
|
|
||||||
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
|
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
|
||||||
return false
|
return false
|
||||||
|
|
||||||
const params: RouterRequestParams = {}
|
const params: RouterRequestParams = {}
|
||||||
|
|
||||||
for (let i = 0; i < routeArr.length; i++) {
|
for (let i = 0; i < routeArr.length; i++) {
|
||||||
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
|
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
|
||||||
return false
|
return false
|
||||||
|
|
||||||
if (routeArr[i][0] === ':')
|
if (routeArr[i][0] === ':')
|
||||||
params[routeArr[i].substring(1)] = pathArr[i]
|
params[routeArr[i].substring(1)] = pathArr[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
request.params = params
|
request.params = params
|
||||||
|
|
||||||
const query: any = {}
|
const query: any = {}
|
||||||
|
|
||||||
for (const [k, v] of url.searchParams.entries()) {
|
for (const [k, v] of url.searchParams.entries()) {
|
||||||
query[k] = v
|
query[k] = v
|
||||||
}
|
}
|
||||||
|
|
||||||
request.query = query
|
request.query = query
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
||||||
}
|
}
|
||||||
@@ -371,12 +388,12 @@ export default class Router {
|
|||||||
/**
|
/**
|
||||||
* Handle requests
|
* Handle requests
|
||||||
*
|
*
|
||||||
* @param {any} env
|
* @param {TEnv} env
|
||||||
* @param {Request} request
|
* @param {Request} request
|
||||||
* @param {any} [extend]
|
* @param {any} [extend]
|
||||||
* @returns {Response}
|
* @returns {Promise<Response>}
|
||||||
*/
|
*/
|
||||||
public async handle(env: any, request: Request, extend: any = {}) {
|
public async handle(env: TEnv, request: Request, extend: any = {}): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
const req: RouterRequest = {
|
const req: RouterRequest = {
|
||||||
...extend,
|
...extend,
|
||||||
@@ -388,17 +405,31 @@ export default class Router {
|
|||||||
query: {},
|
query: {},
|
||||||
body: ''
|
body: ''
|
||||||
}
|
}
|
||||||
if (req.method === 'OPTIONS' && Object.keys(this.corsConfig).length) {
|
|
||||||
return new Response(null, {
|
const headers = new Headers()
|
||||||
headers: {
|
const route = this.getRoute(req)
|
||||||
'Access-Control-Allow-Origin': this.corsConfig.allowOrigin,
|
|
||||||
'Access-Control-Allow-Methods': this.corsConfig.allowMethods,
|
if (this.corsEnabled) {
|
||||||
'Access-Control-Allow-Headers': this.corsConfig.allowHeaders,
|
if (this.corsConfig.allowOrigin)
|
||||||
'Access-Control-Max-Age': this.corsConfig.maxAge!.toString()
|
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||||
},
|
if (this.corsConfig.allowMethods)
|
||||||
status: this.corsConfig.optionsSuccessStatus
|
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||||
})
|
if (this.corsConfig.allowHeaders)
|
||||||
|
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||||
|
if (this.corsConfig.maxAge)
|
||||||
|
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||||
|
|
||||||
|
if (!route && req.method === 'OPTIONS') {
|
||||||
|
return new Response(null, {
|
||||||
|
headers,
|
||||||
|
status: this.corsConfig.optionsSuccessStatus
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!route)
|
||||||
|
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||||
|
|
||||||
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
||||||
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
|
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
|
||||||
try {
|
try {
|
||||||
@@ -414,33 +445,33 @@ export default class Router {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const route = this.getRoute(req)
|
|
||||||
if (!route)
|
const res: RouterResponse = { headers }
|
||||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
|
||||||
const res: RouterResponse = { headers: new Headers() }
|
|
||||||
if (Object.keys(this.corsConfig).length) {
|
|
||||||
res.headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
|
||||||
res.headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
|
||||||
res.headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
|
||||||
res.headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
|
||||||
}
|
|
||||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||||
let prevIndex = -1
|
let prevIndex = -1
|
||||||
|
|
||||||
const runner = async (index: number) => {
|
const runner = async (index: number) => {
|
||||||
if (index === prevIndex)
|
if (index === prevIndex)
|
||||||
throw new Error('next() called multiple times')
|
throw new Error('next() called multiple times')
|
||||||
|
|
||||||
prevIndex = index
|
prevIndex = index
|
||||||
|
|
||||||
if (typeof handlers[index] === 'function')
|
if (typeof handlers[index] === 'function')
|
||||||
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
|
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
|
||||||
}
|
}
|
||||||
|
|
||||||
await runner(0)
|
await runner(0)
|
||||||
|
|
||||||
if (typeof res.body === 'object') {
|
if (typeof res.body === 'object') {
|
||||||
if (!res.headers.has('Content-Type'))
|
if (!res.headers.has('Content-Type'))
|
||||||
res.headers.set('Content-Type', 'application/json')
|
res.headers.set('Content-Type', 'application/json')
|
||||||
|
|
||||||
res.body = JSON.stringify(res.body)
|
res.body = JSON.stringify(res.body)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (res.raw)
|
if (res.raw)
|
||||||
return res.raw
|
return res.raw
|
||||||
|
|
||||||
return new Response([101, 204, 205, 304].includes(res.status || (res.body ? 200 : 204)) ? null : res.body, { status: res.status, headers: res.headers, webSocket: res.webSocket || null })
|
return new Response([101, 204, 205, 304].includes(res.status || (res.body ? 200 : 204)) ? null : res.body, { status: res.status, headers: res.headers, webSocket: res.webSocket || null })
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
|
|||||||
Reference in New Issue
Block a user