Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
eeb1b69e62
|
|||
|
a80cf9ea2e
|
|||
|
c41e3e95f9
|
|||
|
61ad67766f
|
|||
|
c6dfaa3158
|
|||
|
215a3731da
|
|||
|
ad4557ecb3
|
|||
|
2529e5ce24
|
|||
|
42de017ba0
|
|||
|
81dd03af27
|
|||
|
7fe0a5405f
|
|||
|
|
05984eb7da | ||
|
|
ba371dcc6d | ||
|
|
aeb4eb06e4 | ||
|
efd74609f1
|
|||
|
|
fbc862a1f0 | ||
|
01487748af
|
|||
|
|
3374b92075
|
||
|
e8212b5fa8
|
|||
|
|
ded6b81e28 | ||
|
|
972dc916f7 | ||
|
d3b86f1dbe
|
|||
|
aadb398b48
|
|||
|
5fa3475a20
|
|||
|
0637549e90
|
|||
|
f3279e71fc
|
|||
|
bdb7be3699
|
|||
|
45a781ea66
|
|||
|
7f44f304a2
|
|||
|
a786262ec6
|
9
.editorconfig
Normal file
9
.editorconfig
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
end_of_line = lf
|
||||||
|
insert_final_newline = false
|
||||||
|
|
||||||
|
[src/**.ts]
|
||||||
|
charset = utf-8
|
||||||
|
indent_style = tab
|
||||||
286
README.md
286
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.0K 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,81 +9,172 @@ 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.0K gzipped)
|
||||||
|
- Fully written in TypeScript
|
||||||
|
- Integrated Debug-Mode & CORS helper
|
||||||
|
- Built specifically around Middlewares
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Simple Example
|
### TypeScript Example
|
||||||
|
|
||||||
```javascript
|
```typescript
|
||||||
import Router from '@tsndr/cloudflare-worker-router'
|
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
|
||||||
|
|
||||||
|
SECRET_TOKEN: string
|
||||||
|
}
|
||||||
|
|
||||||
// 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(() => {
|
||||||
res.headers.set('X-Global-Middlewares', 'true')
|
return new Response(null, {
|
||||||
next()
|
headers: {
|
||||||
|
'X-Global-Middlewares': 'true'
|
||||||
|
}
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Simple get
|
// Simple get
|
||||||
router.get('/user', ({ req, res }) => {
|
router.get('/user', () => {
|
||||||
res.body = {
|
return Response.json({
|
||||||
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 }) => {
|
||||||
|
|
||||||
const userId = req.params.id
|
const userId = req.params.id
|
||||||
|
|
||||||
// Do stuff...
|
// Do stuff
|
||||||
|
|
||||||
if (errorDoingStuff) {
|
if (!true) {
|
||||||
res.status = 400
|
return Response.json({
|
||||||
res.body = {
|
error: 'Error doing stuff!'
|
||||||
error: 'User did stupid stuff!'
|
}, { status: 400 })
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
return Response.json({ userId }, { 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', ({ env, req }) => {
|
||||||
|
const { SECRET_TOKEN } = env
|
||||||
|
|
||||||
if (!apiTokenIsCorrect) {
|
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||||
res.status = 401
|
return new Response(null, { status: 401 })
|
||||||
return
|
|
||||||
}
|
}, ({ req }) => {
|
||||||
|
|
||||||
await next()
|
|
||||||
}, (req, res) => {
|
|
||||||
|
|
||||||
const userId = req.params.id
|
const userId = req.params.id
|
||||||
|
|
||||||
// Do stuff...
|
// Do stuff...
|
||||||
|
|
||||||
|
return Response.json({ userId })
|
||||||
})
|
})
|
||||||
|
|
||||||
// Listen Cloudflare Workers Fetch Event
|
// Listen Cloudflare Workers Fetch Event
|
||||||
export default {
|
export default {
|
||||||
async fetch(request, env) {
|
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||||
return router.handle(env, request)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
<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(() => {
|
||||||
|
return new Response(null, {
|
||||||
|
headers: {
|
||||||
|
'X-Global-Middlewares': 'true'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Simple get
|
||||||
|
router.get('/user', () => {
|
||||||
|
return Response.json({
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Post route with url parameter
|
||||||
|
router.post('/user/:id', ({ req }) => {
|
||||||
|
const userId = req.params.id
|
||||||
|
|
||||||
|
// Do stuff
|
||||||
|
|
||||||
|
if (errorDoingStuff) {
|
||||||
|
return Response.json({
|
||||||
|
error: 'Error doing stuff!'
|
||||||
|
}, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json({ userId }, { status: 204 })
|
||||||
|
})
|
||||||
|
|
||||||
|
// Delete route using a middleware
|
||||||
|
router.delete('/user/:id', ({ env, req }) => {
|
||||||
|
const { SECRET_TOKEN } = env
|
||||||
|
|
||||||
|
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||||
|
return new Response(null, { status: 401 })
|
||||||
|
|
||||||
|
}, ({ req }) => {
|
||||||
|
const userId = req.params.id
|
||||||
|
|
||||||
|
// Do stuff...
|
||||||
|
|
||||||
|
return Response.json({ userId })
|
||||||
|
})
|
||||||
|
|
||||||
|
// Listen Cloudflare Workers Fetch Event
|
||||||
|
export default {
|
||||||
|
async fetch(request, env, ctx) {
|
||||||
|
return router.handle(request, env, ctx)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
@@ -96,6 +187,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,8 +201,10 @@ 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)
|
||||||
|
|
||||||
|
|
||||||
### `router.cors([config])`
|
### `router.cors([config])`
|
||||||
@@ -126,16 +223,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)
|
||||||
|
|
||||||
@@ -145,16 +245,16 @@ Supports the use of dynamic parameters, prefixed with a `:` (i.e. `/user/:userId
|
|||||||
|
|
||||||
#### `handlers` (function, optional)
|
#### `handlers` (function, optional)
|
||||||
|
|
||||||
An unlimited number of functions getting [`req`](#req-object) and [`res`](#res-object) passed into them.
|
An unlimited number of functions getting [`ctx`](#ctx-object) passed into them.
|
||||||
|
|
||||||
|
|
||||||
### `ctx`-Object
|
### `ctx`-Object
|
||||||
|
|
||||||
Key | Type | Description
|
Key | Type | Description
|
||||||
--------- | ------------------- | -----------
|
--------- | ------------------- | -----------
|
||||||
`env` | `object` | Environment
|
`env` | `object` | Environment
|
||||||
`req` | `req`-Object | Request Object
|
`req` | `req`-Object | Request Object
|
||||||
`res` | `res`-Object | Response Object
|
`ctx` | `ctx`-Object | Cloudflare's `ctx`-Object
|
||||||
`next` | `next`-Handler | Next Handler
|
|
||||||
|
|
||||||
|
|
||||||
### `req`-Object
|
### `req`-Object
|
||||||
@@ -168,83 +268,87 @@ Key | Type | Description
|
|||||||
`query` | `object` | Object containing all query parameters
|
`query` | `object` | Object containing all query parameters
|
||||||
|
|
||||||
|
|
||||||
### `res`-Object
|
|
||||||
|
|
||||||
Key | Type | Description
|
|
||||||
----------- | ------------------- | -----------
|
|
||||||
`body` | `object` / `string` | Either set an `object` (will be converted to JSON) or a string
|
|
||||||
`headers` | `Headers` | Response [Headers Object](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
|
|
||||||
`status` | `integer` | Return status code (default: `204`)
|
|
||||||
`webSocket` | `WebSocket` | Upgraded websocket connection
|
|
||||||
|
|
||||||
|
|
||||||
## 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
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||||
return router.handle(env, request)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
</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 {
|
||||||
async fetch(request, env, ctx) {
|
async fetch(request, env, ctx) {
|
||||||
return router.handle(env, request)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
</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.1.0",
|
"version": "3.0.0-0",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "2.1.0",
|
"version": "3.0.0-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.1.0",
|
"version": "3.0.0-0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
|
|||||||
772
src/index.ts
772
src/index.ts
@@ -1,448 +1,424 @@
|
|||||||
/**
|
/**
|
||||||
* Route Object
|
* Route Object
|
||||||
*
|
*
|
||||||
* @typedef Route
|
* @typedef Route
|
||||||
* @property {string} method HTTP request method
|
* @property {string} method HTTP request method
|
||||||
* @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 {RouterEnv} env Environment
|
* @property {RouterEnv} env Environment
|
||||||
* @property {RouterRequest} req Request Object
|
* @property {RouterRequest} req Request Object
|
||||||
* @property {RouterResponse} res Response Object
|
* @property {ExecutionContext} ctx Context Object
|
||||||
* @property {RouterNext} next Next Handler
|
*/
|
||||||
*/
|
export interface RouterContext<TEnv = any> {
|
||||||
export interface RouterContext {
|
env: TEnv
|
||||||
env: any
|
req: RouterRequest
|
||||||
req: RouterRequest
|
ctx: ExecutionContext
|
||||||
res: RouterResponse
|
|
||||||
next: RouterNext
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request Object
|
* Request Object
|
||||||
*
|
*
|
||||||
* @typedef RouterRequest
|
* @typedef RouterRequest
|
||||||
* @property {string} url URL
|
* @property {string} url URL
|
||||||
* @property {string} method HTTP request method
|
* @property {string} method HTTP request method
|
||||||
* @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 {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 {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 {
|
||||||
url: string
|
url: string
|
||||||
method: string
|
method: string
|
||||||
params: RouterRequestParams
|
params: RouterRequestParams
|
||||||
query: RouterRequestQuery
|
query: RouterRequestQuery
|
||||||
headers: Headers
|
headers: Headers
|
||||||
body: string | any
|
body: string | any
|
||||||
cf?: IncomingRequestCfProperties
|
cf?: IncomingRequestCfProperties
|
||||||
[key: string]: any
|
[key: string]: any
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request Parameters
|
* Request Parameters
|
||||||
*
|
*
|
||||||
* @typedef RouterRequestParams
|
* @typedef RouterRequestParams
|
||||||
*/
|
*/
|
||||||
export interface RouterRequestParams {
|
export interface RouterRequestParams {
|
||||||
[key: string]: string
|
[key: string]: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request Query
|
* Request Query
|
||||||
*
|
*
|
||||||
* @typedef RouterRequestQuery
|
* @typedef RouterRequestQuery
|
||||||
*/
|
*/
|
||||||
export interface RouterRequestQuery {
|
export interface RouterRequestQuery {
|
||||||
[key: string]: string
|
[key: string]: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Response Object
|
* Handler Function
|
||||||
*
|
*
|
||||||
* @typedef RouterResponse
|
* @callback RouterHandler
|
||||||
* @property {Headers} headers Response headers object
|
* @param {RouterContext} ctx
|
||||||
* @property {number} [status=204] Return status code (default: `204`)
|
* @returns {Promise<Response | void> Response | void}
|
||||||
* @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.
|
export interface RouterHandler<TEnv = any> {
|
||||||
*/
|
(ctx: RouterContext<TEnv>): Promise<Response | void> | Response | void
|
||||||
export interface RouterResponse {
|
|
||||||
headers: Headers
|
|
||||||
status?: number
|
|
||||||
body?: string | any
|
|
||||||
raw?: Response,
|
|
||||||
webSocket?: WebSocket
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Next Function
|
* CORS Config
|
||||||
*
|
*
|
||||||
* @callback RouterNext
|
* @typedef RouterCorsConfig
|
||||||
* @returns {Promise<void>}
|
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
|
||||||
*/
|
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
|
||||||
export interface RouterNext {
|
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
|
||||||
(): Promise<void>
|
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
||||||
}
|
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||||
|
*/
|
||||||
/**
|
|
||||||
* Handler Function
|
|
||||||
*
|
|
||||||
* @callback RouterHandler
|
|
||||||
* @param {RouterContext} ctx
|
|
||||||
* @returns {Promise<void> | void}
|
|
||||||
*/
|
|
||||||
export interface RouterHandler {
|
|
||||||
(ctx: RouterContext): Promise<void> | void
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CORS Config
|
|
||||||
*
|
|
||||||
* @typedef RouterCorsConfig
|
|
||||||
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
|
|
||||||
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
|
|
||||||
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
|
|
||||||
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
|
||||||
* @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
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router
|
* Router
|
||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
* @class
|
* @class
|
||||||
*/
|
*/
|
||||||
export default class Router {
|
export class Router<TEnv = any> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Array
|
* Router Array
|
||||||
*
|
*
|
||||||
* @protected
|
* @protected
|
||||||
* @type {Route[]}
|
* @type {Route[]}
|
||||||
*/
|
*/
|
||||||
protected routes: Route[] = []
|
protected routes: Route<TEnv>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global Handlers
|
* Global Handlers
|
||||||
*
|
*
|
||||||
* @protected
|
* @protected
|
||||||
* @type {RouterHandler[]}
|
* @type {RouterHandler[]}
|
||||||
*/
|
*/
|
||||||
protected globalHandlers: RouterHandler[] = []
|
protected globalHandlers: RouterHandler<TEnv>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Debug Mode
|
* Debug Mode
|
||||||
*
|
*
|
||||||
* @protected
|
* @protected
|
||||||
* @type {boolean}
|
* @type {boolean}
|
||||||
*/
|
*/
|
||||||
protected debugMode: boolean = false
|
protected debugMode: boolean = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CORS Config
|
* CORS Config
|
||||||
*
|
*
|
||||||
* @protected
|
* @protected
|
||||||
* @type {RouterCorsConfig}
|
* @type {RouterCorsConfig}
|
||||||
*/
|
*/
|
||||||
protected corsConfig: RouterCorsConfig = {}
|
protected corsConfig: RouterCorsConfig = {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register global handlers
|
* CORS enabled
|
||||||
*
|
*
|
||||||
* @param {RouterHandler[]} handlers
|
* @protected
|
||||||
* @returns {Router}
|
* @type {boolean}
|
||||||
*/
|
*/
|
||||||
public use(...handlers: RouterHandler[]): Router {
|
protected corsEnabled: boolean = false
|
||||||
for (let handler of handlers) {
|
|
||||||
this.globalHandlers.push(handler)
|
|
||||||
}
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register CONNECT route
|
* Register global handlers
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {RouterHandler[]} handlers
|
||||||
* @param {RouterHandler[]} handlers
|
* @returns {Router}
|
||||||
* @returns {Router}
|
*/
|
||||||
*/
|
public use(...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
public connect(url: string, ...handlers: RouterHandler[]): Router {
|
for (let handler of handlers) {
|
||||||
return this.register('CONNECT', url, handlers)
|
this.globalHandlers.push(handler)
|
||||||
}
|
}
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register DELETE route
|
* Register CONNECT route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public delete(url: string, ...handlers: RouterHandler[]): Router {
|
public connect(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('DELETE', url, handlers)
|
return this.register('CONNECT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register GET route
|
* Register DELETE route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public get(url: string, ...handlers: RouterHandler[]): Router {
|
public delete(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('GET', url, handlers)
|
return this.register('DELETE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register HEAD route
|
* Register GET route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public head(url: string, ...handlers: RouterHandler[]): Router {
|
public get(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('HEAD', url, handlers)
|
return this.register('GET', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register OPTIONS route
|
* Register HEAD route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public options(url: string, ...handlers: RouterHandler[]): Router {
|
public head(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('OPTIONS', url, handlers)
|
return this.register('HEAD', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register PATCH route
|
* Register OPTIONS route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public patch(url: string, ...handlers: RouterHandler[]): Router {
|
public options(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('PATCH', url, handlers)
|
return this.register('OPTIONS', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register POST route
|
* Register PATCH route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public post(url: string, ...handlers: RouterHandler[]): Router {
|
public patch(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('POST', url, handlers)
|
return this.register('PATCH', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register PUT route
|
* Register POST route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public put(url: string, ...handlers: RouterHandler[]): Router {
|
public post(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('PUT', url, handlers)
|
return this.register('POST', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register TRACE route
|
* Register PUT route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public trace(url: string, ...handlers: RouterHandler[]): Router {
|
public put(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('TRACE', url, handlers)
|
return this.register('PUT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register route, ignoring method
|
* Register TRACE route
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public any(url: string, ...handlers: RouterHandler[]): Router {
|
public trace(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this.register('*', url, handlers)
|
return this.register('TRACE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Debug Mode
|
* Register route, ignoring method
|
||||||
*
|
*
|
||||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
* @param {string} url
|
||||||
* @returns {Router}
|
* @param {RouterHandler[]} handlers
|
||||||
*/
|
* @returns {Router}
|
||||||
public debug(state: boolean = true): Router {
|
*/
|
||||||
this.debugMode = state
|
public any(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
return this
|
return this.register('*', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enable CORS support
|
* Debug Mode
|
||||||
*
|
*
|
||||||
* @param {RouterCorsConfig} [config]
|
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public cors(config?: RouterCorsConfig): Router {
|
public debug(state: boolean = true): Router<TEnv> {
|
||||||
this.corsConfig = {
|
this.debugMode = state
|
||||||
allowOrigin: config?.allowOrigin || '*',
|
return this
|
||||||
allowMethods: config?.allowMethods || '*',
|
}
|
||||||
allowHeaders: config?.allowHeaders || '*, Authorization',
|
|
||||||
maxAge: config?.maxAge || 86400,
|
|
||||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
|
||||||
}
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register route
|
* Enable CORS support
|
||||||
*
|
*
|
||||||
* @private
|
* @param {RouterCorsConfig} [config]
|
||||||
* @param {string} method HTTP request method
|
* @returns {Router}
|
||||||
* @param {string} url URL String
|
*/
|
||||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
public cors(config?: RouterCorsConfig): Router<TEnv> {
|
||||||
* @returns {Router}
|
this.corsEnabled = true
|
||||||
*/
|
this.corsConfig = {
|
||||||
private register(method: string, url: string, handlers: RouterHandler[]): Router {
|
allowOrigin: config?.allowOrigin || '*',
|
||||||
this.routes.push({
|
allowMethods: config?.allowMethods || '*',
|
||||||
method,
|
allowHeaders: config?.allowHeaders || '*',
|
||||||
url,
|
maxAge: config?.maxAge || 86400,
|
||||||
handlers
|
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||||
})
|
}
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private setCorsHeaders(headers: Headers = new Headers()): Headers {
|
||||||
* Get Route by request
|
if (this.corsConfig.allowOrigin && !headers.has('Access-Control-Allow-Origin'))
|
||||||
*
|
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||||
* @private
|
if (this.corsConfig.allowMethods && !headers.has('Access-Control-Allow-Methods'))
|
||||||
* @param {RouterRequest} request
|
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||||
* @returns {Route | undefined}
|
if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
|
||||||
*/
|
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||||
private getRoute(request: RouterRequest): Route | undefined {
|
if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
|
||||||
const url = new URL(request.url)
|
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||||
const pathArr = url.pathname.split('/').filter(i => i)
|
return headers
|
||||||
return this.routes.find(r => {
|
}
|
||||||
const routeArr = r.url.split('/').filter(i => i)
|
|
||||||
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
|
|
||||||
return false
|
|
||||||
const params: RouterRequestParams = {}
|
|
||||||
for (let i = 0; i < routeArr.length; i++) {
|
|
||||||
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
|
|
||||||
return false
|
|
||||||
if (routeArr[i][0] === ':')
|
|
||||||
params[routeArr[i].substring(1)] = pathArr[i]
|
|
||||||
}
|
|
||||||
request.params = params
|
|
||||||
const query: any = {}
|
|
||||||
for (const [k, v] of url.searchParams.entries()) {
|
|
||||||
query[k] = v
|
|
||||||
}
|
|
||||||
request.query = query
|
|
||||||
return true
|
|
||||||
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle requests
|
* Register route
|
||||||
*
|
*
|
||||||
* @param {any} env
|
* @private
|
||||||
* @param {Request} request
|
* @param {string} method HTTP request method
|
||||||
* @param {any} [extend]
|
* @param {string} url URL String
|
||||||
* @returns {Response}
|
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||||
*/
|
* @returns {Router}
|
||||||
public async handle(env: any, request: Request, extend: any = {}) {
|
*/
|
||||||
try {
|
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
||||||
const req: RouterRequest = {
|
this.routes.push({
|
||||||
...extend,
|
method,
|
||||||
method: request.method,
|
url,
|
||||||
headers: request.headers,
|
handlers
|
||||||
url: request.url,
|
})
|
||||||
cf: request.cf,
|
|
||||||
params: {},
|
|
||||||
query: {},
|
|
||||||
body: ''
|
|
||||||
}
|
|
||||||
|
|
||||||
const headers = new Headers()
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
if (this.corsConfig.allowOrigin)
|
/**
|
||||||
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
* Get Route by request
|
||||||
if (this.corsConfig.allowMethods)
|
*
|
||||||
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
* @private
|
||||||
if (this.corsConfig.allowHeaders)
|
* @param {RouterRequest} request
|
||||||
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
* @returns {Route | undefined}
|
||||||
if (this.corsConfig.maxAge)
|
*/
|
||||||
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
private getRoute(request: RouterRequest): Route<TEnv> | undefined {
|
||||||
|
const url = new URL(request.url)
|
||||||
|
const pathArr = url.pathname.split('/').filter(i => i)
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
return this.routes.find(r => {
|
||||||
return new Response(null, {
|
const routeArr = r.url.split('/').filter(i => i)
|
||||||
headers,
|
|
||||||
status: this.corsConfig.optionsSuccessStatus
|
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
|
||||||
})
|
return false
|
||||||
}
|
|
||||||
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
const params: RouterRequestParams = {}
|
||||||
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
|
|
||||||
try {
|
for (let i = 0; i < routeArr.length; i++) {
|
||||||
req.body = await request.json()
|
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
|
||||||
} catch {
|
return false
|
||||||
req.body = {}
|
|
||||||
}
|
if (routeArr[i][0] === ':')
|
||||||
} else {
|
params[routeArr[i].substring(1)] = pathArr[i]
|
||||||
try {
|
}
|
||||||
req.body = await request.text()
|
|
||||||
} catch {
|
request.params = params
|
||||||
req.body = ''
|
|
||||||
}
|
const query: any = {}
|
||||||
}
|
|
||||||
}
|
for (const [k, v] of url.searchParams.entries()) {
|
||||||
const route = this.getRoute(req)
|
query[k] = v
|
||||||
if (!route)
|
}
|
||||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
|
||||||
const res: RouterResponse = { headers }
|
request.query = query
|
||||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
|
||||||
let prevIndex = -1
|
return true
|
||||||
const runner = async (index: number) => {
|
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
||||||
if (index === prevIndex)
|
}
|
||||||
throw new Error('next() called multiple times')
|
|
||||||
prevIndex = index
|
/**
|
||||||
if (typeof handlers[index] === 'function')
|
* Handle requests
|
||||||
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
|
*
|
||||||
}
|
* @param {TEnv} env
|
||||||
await runner(0)
|
* @param {Request} request
|
||||||
if (typeof res.body === 'object') {
|
* @param {any} [extend]
|
||||||
if (!res.headers.has('Content-Type'))
|
* @returns {Promise<Response>}
|
||||||
res.headers.set('Content-Type', 'application/json')
|
*/
|
||||||
res.body = JSON.stringify(res.body)
|
public async handle(request: Request, env: TEnv, ctx: ExecutionContext, extend: any = {}): Promise<Response> {
|
||||||
}
|
const req: RouterRequest = {
|
||||||
if (res.raw)
|
...extend,
|
||||||
return res.raw
|
method: request.method,
|
||||||
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 })
|
headers: request.headers,
|
||||||
} catch(err) {
|
url: request.url,
|
||||||
console.error(err)
|
cf: request.cf,
|
||||||
return new Response(this.debugMode && err instanceof Error ? err.stack : '', { status: 500 })
|
params: {},
|
||||||
}
|
query: {},
|
||||||
}
|
body: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const route = this.getRoute(req)
|
||||||
|
|
||||||
|
if (!route)
|
||||||
|
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||||
|
|
||||||
|
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||||
|
return new Response(null, {
|
||||||
|
headers: this.setCorsHeaders(),
|
||||||
|
status: this.corsConfig.optionsSuccessStatus
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||||
|
|
||||||
|
let response: Response | undefined
|
||||||
|
|
||||||
|
for (const handler of handlers) {
|
||||||
|
const res = await handler({ env, req, ctx })
|
||||||
|
|
||||||
|
if (res) {
|
||||||
|
response = res
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response)
|
||||||
|
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
||||||
|
|
||||||
|
if (this.corsEnabled)
|
||||||
|
this.setCorsHeaders(response.headers)
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@
|
|||||||
"alwaysStrict": true,
|
"alwaysStrict": true,
|
||||||
"noUnusedLocals": true,
|
"noUnusedLocals": true,
|
||||||
"noUnusedParameters": true,
|
"noUnusedParameters": true,
|
||||||
"noImplicitReturns": true,
|
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"preserveConstEnums": true,
|
"preserveConstEnums": true,
|
||||||
@@ -24,4 +23,4 @@
|
|||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user