Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
0a73e4c32e
|
|||
|
8bd8e50ee5
|
|||
|
e4ec06bf47
|
|||
|
2ad75dc3fb
|
|||
|
c2b6189a86
|
|||
|
33cafbf17c
|
|||
|
1e78778ba0
|
|||
|
b0d05656bb
|
|||
|
d4ba12a517
|
|||
|
b48e5c2333
|
|||
|
bf41e2c193
|
|||
|
5342cfd310
|
|||
|
8f400ff5b7
|
|||
|
51f30f642f
|
|||
|
bcab122e15
|
|||
|
f3181ca9a5
|
|||
|
7edfc835fa
|
|||
|
7300e36469
|
|||
|
e122feadb5
|
|||
|
ceed474f24
|
|||
|
864b7f153c
|
|||
|
6a2173cdbc
|
|||
|
87a3d344d9
|
|||
|
9f96fd112e
|
|||
|
5f34e30c1e
|
|||
|
b38baf7d62
|
|||
|
07cb83ff9f
|
|||
|
2a064dcb9c
|
|||
|
5e18d06dfd
|
|||
|
4f169120de
|
|||
|
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
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Publish (main)
|
||||
name: Publish (pre)
|
||||
|
||||
on:
|
||||
release:
|
||||
@@ -20,11 +20,11 @@ jobs:
|
||||
- name: Publish to npmjs
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
run: npm publish --tag latest --access public
|
||||
run: npm publish --tag pre --access public
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
registry-url: https://npm.pkg.github.com/
|
||||
- name: Publish to GPR
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
run: npm publish --tag latest --access public
|
||||
run: npm publish --tag pre --access public
|
||||
@@ -4,3 +4,4 @@ test/
|
||||
.nvmrc
|
||||
MIGRATION.md
|
||||
tsconfig.json
|
||||
.editorconfig
|
||||
93
MIGRATION.md
93
MIGRATION.md
@@ -1,71 +1,70 @@
|
||||
# Migration Guide
|
||||
|
||||
From `v1.x.x` to `v2.x.x`.
|
||||
From `v2.x.x` to `v3.x.x`.
|
||||
|
||||
|
||||
## Contents
|
||||
|
||||
- [Preparation](#preparation)
|
||||
- [Update](#update)
|
||||
- [Import / Require](#import--require)
|
||||
- [Routes](#routes)
|
||||
- [Update Router](#update-router)
|
||||
- [Handlers](#handlers)
|
||||
- [Fetch](#fetch--routerhandle)
|
||||
|
||||
|
||||
## Preparation
|
||||
## Update Router
|
||||
|
||||
Follow Cloudflare's [Migration Guide](https://developers.cloudflare.com/workers/wrangler/migration/migrating-from-wrangler-1/) to update your protject to [wrangler2](https://github.com/cloudflare/wrangler2).
|
||||
|
||||
## Update
|
||||
|
||||
Update to the latest version verstion
|
||||
Update to the latest version version of the router.
|
||||
|
||||
```bash
|
||||
npm i -D @tsndr/cloudflare-worker-router
|
||||
```
|
||||
|
||||
## Import / Require
|
||||
|
||||
Switch to ESModules.
|
||||
## Handlers
|
||||
|
||||
- Remove `res` and `next` from handler parameter list.
|
||||
- Replace `res.` with `return new Response()` / `return Response.json()`.
|
||||
- Remove `next()` calls from middlewares.
|
||||
|
||||
|
||||
### Before
|
||||
|
||||
```javascript
|
||||
const Router = require('@tsndr/cloudflare-worker-router')
|
||||
```typescript
|
||||
// Register global middleware
|
||||
router.use(({ env, req, res, next }) => {
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
|
||||
res.status = 401
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
|
||||
// Simple get
|
||||
router.get('/user', ({ res }) => {
|
||||
res.body = {
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### After
|
||||
|
||||
```javascript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
```typescript
|
||||
// Register global middleware
|
||||
router.use(({ env, req }) => {
|
||||
// Intercept if token doesn't match
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
|
||||
return new Response(null, { status: 401 })
|
||||
}
|
||||
})
|
||||
|
||||
// Simple get
|
||||
router.get('/user', () => {
|
||||
return Response.json({
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Routes
|
||||
|
||||
Just add curly braces.
|
||||
|
||||
|
||||
### Before
|
||||
|
||||
<a href="https://gist.github.com/tsndr/34e8544266ae15d51abd019d7c3d27ca" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 57 01 PM" src="https://user-images.githubusercontent.com/2940127/175572731-a8729c1b-15e2-45ac-be80-7e8527c5502a.png"></a>
|
||||
|
||||
|
||||
### After
|
||||
|
||||
<a href="https://gist.github.com/tsndr/8db6e8dd55e348015c2ff8e93dd6aa31" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 55 56 PM" src="https://user-images.githubusercontent.com/2940127/175572549-0eea8fc4-3d90-412a-89cc-d2f4569f1139.png"></a>
|
||||
|
||||
|
||||
## Fetch / `router.handle()`
|
||||
|
||||
❗️ Be aware that with `v2.0.0` the parameters of `router.handle()` changed ❗️
|
||||
|
||||
|
||||
### Before
|
||||
|
||||
<a href="https://gist.github.com/tsndr/12b0f800269760c597646c90a562ef88" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 58 43 PM" src="https://user-images.githubusercontent.com/2940127/175572993-fb4681c2-eece-4c92-88e8-1c2f57644769.png"></a>
|
||||
|
||||
|
||||
### After
|
||||
|
||||
<a href="https://gist.github.com/tsndr/30902b01b134e2a58cf3a53648dd3e47" target="_blank"><img width="393" alt="Petrify 2022-06-24 at 5 59 22 PM" src="https://user-images.githubusercontent.com/2940127/175573110-b7dfcfb2-855d-4529-a957-6f8b9ec439f3.png"></a>
|
||||
|
||||
290
README.md
290
README.md
@@ -1,6 +1,6 @@
|
||||
# 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.
|
||||
|
||||
@@ -9,81 +9,168 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
||||
|
||||
## Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Usage](#usage)
|
||||
- [Reference](#reference)
|
||||
- [Setup](#setup)
|
||||
- [Getting started](#getting-started)
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
- ZERO dependencies
|
||||
- Lightweight (1.0K gzipped)
|
||||
- Fully written in TypeScript
|
||||
- Integrated Debug-Mode & CORS helper
|
||||
- Built specifically around Middlewares
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
### Simple Example
|
||||
Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
|
||||
|
||||
```javascript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
### TypeScript Example
|
||||
|
||||
```typescript
|
||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
export type 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
|
||||
const router = new Router()
|
||||
const router = new Router<Env>()
|
||||
|
||||
// Enabling buildin CORS support
|
||||
// Enabling build in CORS support
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
router.use(({ req, res, next }) => {
|
||||
res.headers.set('X-Global-Middlewares', 'true')
|
||||
next()
|
||||
router.use(({ env, req }) => {
|
||||
// Intercept if token doesn't match
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
})
|
||||
|
||||
// Simple get
|
||||
router.get('/user', ({ req, res }) => {
|
||||
res.body = {
|
||||
data: {
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
}
|
||||
}
|
||||
router.get('/user', () => {
|
||||
return Response.json({
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
})
|
||||
})
|
||||
|
||||
// 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) {
|
||||
res.status = 400
|
||||
res.body = {
|
||||
error: 'User did stupid stuff!'
|
||||
if (!true) {
|
||||
return Response.json({
|
||||
error: 'Error doing stuff!'
|
||||
}, { status: 400 })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
res.status = 204
|
||||
return Response.json({ userId }, { status: 204 })
|
||||
})
|
||||
|
||||
// Delete route using a middleware
|
||||
router.delete('/user/:id', ({ req, res, next }) => {
|
||||
router.delete('/user/:id', ({ env, req }) => {
|
||||
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
|
||||
if (!apiTokenIsCorrect) {
|
||||
res.status = 401
|
||||
return
|
||||
}
|
||||
|
||||
await next()
|
||||
}, (req, res) => {
|
||||
}, ({ req }) => {
|
||||
|
||||
const userId = req.params.id
|
||||
|
||||
// Do stuff...
|
||||
|
||||
return Response.json({ userId })
|
||||
})
|
||||
|
||||
// Listen Cloudflare Workers Fetch Event
|
||||
export default {
|
||||
async fetch(request, env) {
|
||||
return router.handle(env, request)
|
||||
}
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||
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(({ env, req }) => {
|
||||
// Intercept if token doesn't match
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
})
|
||||
|
||||
// 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 (!true) {
|
||||
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 }) => {
|
||||
if (req.headers.get('authorization') === env.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
|
||||
@@ -96,6 +183,10 @@ Enable or disable debug mode. Which will return the `error.stack` in case of an
|
||||
#### `state`
|
||||
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])`
|
||||
|
||||
@@ -106,8 +197,10 @@ Register a global middleware handler.
|
||||
|
||||
Handler is a `function` which will be called for every request.
|
||||
|
||||
|
||||
#### `ctx`
|
||||
Object containing `env`, [`req`](#req-object), [`res`](#res-object), `next`
|
||||
|
||||
Object containing `env`, [`req`](#req-object)
|
||||
|
||||
|
||||
### `router.cors([config])`
|
||||
@@ -126,16 +219,19 @@ Key | Type | Default Value
|
||||
`optionsSuccessStatus` | `integer` | `204`
|
||||
|
||||
|
||||
### `router.any(url, [...handlers])`
|
||||
### `router.connect(url, [...handlers])`
|
||||
### `router.delete(url, [...handlers])`
|
||||
### `router.get(url, [...handlers])`
|
||||
### `router.head(url, [...handlers])`
|
||||
### `router.options(url, [...handlers])`
|
||||
### `router.patch(url, [...handlers])`
|
||||
### `router.post(url, [...handlers])`
|
||||
### `router.put(url, [...handlers])`
|
||||
### `router.trace(url, [...handlers])`
|
||||
### Supported Methods
|
||||
|
||||
- `router.any(url, [...handlers])`
|
||||
- `router.connect(url, [...handlers])`
|
||||
- `router.delete(url, [...handlers])`
|
||||
- `router.get(url, [...handlers])`
|
||||
- `router.head(url, [...handlers])`
|
||||
- `router.options(url, [...handlers])`
|
||||
- `router.patch(url, [...handlers])`
|
||||
- `router.post(url, [...handlers])`
|
||||
- `router.put(url, [...handlers])`
|
||||
- `router.trace(url, [...handlers])`
|
||||
|
||||
|
||||
#### `url` (string)
|
||||
|
||||
@@ -145,16 +241,16 @@ Supports the use of dynamic parameters, prefixed with a `:` (i.e. `/user/:userId
|
||||
|
||||
#### `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
|
||||
|
||||
Key | Type | Description
|
||||
--------- | ------------------- | -----------
|
||||
`env` | `object` | Environment
|
||||
`req` | `req`-Object | Request Object
|
||||
`res` | `res`-Object | Response Object
|
||||
`next` | `next`-Handler | Next Handler
|
||||
`ctx` | `ctx`-Object | Cloudflare's `ctx`-Object
|
||||
|
||||
|
||||
### `req`-Object
|
||||
@@ -168,83 +264,97 @@ Key | Type | Description
|
||||
`query` | `object` | Object containing all query parameters
|
||||
|
||||
|
||||
### `res`-Object
|
||||
## Getting started
|
||||
|
||||
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
|
||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
|
||||
|
||||
|
||||
## Setup
|
||||
#### Initialize Project
|
||||
|
||||
---
|
||||
### ❗️ Compatibility ❗️
|
||||
```bash
|
||||
wrangler init <name>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
### **[Wrangler2](https://github.com/cloudflare/wrangler2#readme)**
|
||||
|
||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/), then install the router using this command
|
||||
Use of TypeScript is strongly encouraged :)
|
||||
|
||||
```bash
|
||||
npm i -D @tsndr/cloudflare-worker-router
|
||||
```
|
||||
|
||||
and replace your `index.ts` / `index.js` with one of the following scripts
|
||||
|
||||
<details>
|
||||
<summary>TypeScript (<code>src/index.ts</code>)</summary>
|
||||
### TypeScript (<code>src/index.ts</code>)
|
||||
|
||||
```typescript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
export interface Env {
|
||||
export type Env = {
|
||||
// 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/
|
||||
// MY_DURABLE_OBJECT: DurableObjectNamespace;
|
||||
// MY_DURABLE_OBJECT: DurableObjectNamespace
|
||||
//
|
||||
// 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', async () => {
|
||||
// return new Response('Hello World')
|
||||
//})
|
||||
|
||||
|
||||
/// Example Route for splitting into multiple files
|
||||
//
|
||||
// const hiHandler: RouteHandler<Env> = async () => {
|
||||
// return new Response('Hello World')
|
||||
// }
|
||||
//
|
||||
// router.get('/hi', hiHandler)
|
||||
|
||||
|
||||
// TODO: add your routes here
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
||||
return router.handle(env, request)
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||
return router.handle(request, env, ctx)
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
### JavaScript (<code>src/index.js</code>)
|
||||
|
||||
<details>
|
||||
<summary>JavaScript (<code>src/index.js</code>)</summary>
|
||||
<summary>Consider using TypeScript instead :)</summary>
|
||||
|
||||
```javascript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
const router = new Router()
|
||||
|
||||
/// Example Route
|
||||
//
|
||||
// router.get('/hi', async () => {
|
||||
// return new Response('Hello World')
|
||||
//})
|
||||
|
||||
/// Example Route for splitting into multiple files
|
||||
//
|
||||
// async function hiHandler() {
|
||||
// return new Response('Hello World')
|
||||
// }
|
||||
//
|
||||
// router.get('/hi', hiHandler)
|
||||
|
||||
// TODO: add your routes here
|
||||
|
||||
export default {
|
||||
async fetch(request, env, ctx) {
|
||||
return router.handle(env, request)
|
||||
return router.handle(request, env, ctx)
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
32
package-lock.json
generated
32
package-lock.json
generated
@@ -1,28 +1,28 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "3.0.0-10",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "3.0.0-10",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
"typescript": "^4.7.4"
|
||||
"@cloudflare/workers-types": "^4.20230115.0",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workers-types": {
|
||||
"version": "3.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz",
|
||||
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==",
|
||||
"version": "4.20230115.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
|
||||
"integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "4.7.4",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz",
|
||||
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==",
|
||||
"version": "4.9.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
|
||||
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
@@ -35,15 +35,15 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@cloudflare/workers-types": {
|
||||
"version": "3.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz",
|
||||
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==",
|
||||
"version": "4.20230115.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
|
||||
"integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
|
||||
"dev": true
|
||||
},
|
||||
"typescript": {
|
||||
"version": "4.7.4",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz",
|
||||
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==",
|
||||
"version": "4.9.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
|
||||
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "3.0.0-10",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
"typescript": "^4.7.4"
|
||||
"@cloudflare/workers-types": "^4.20230115.0",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
844
src/index.ts
844
src/index.ts
@@ -1,448 +1,436 @@
|
||||
/**
|
||||
* Route Object
|
||||
*
|
||||
* @typedef Route
|
||||
* @property {string} method HTTP request method
|
||||
* @property {string} url URL String
|
||||
* @property {RouterHandler[]} handlers Array of handler functions
|
||||
*/
|
||||
export interface Route {
|
||||
method: string
|
||||
url: string
|
||||
handlers: RouterHandler[]
|
||||
* Route Object
|
||||
*
|
||||
* @typedef Route
|
||||
* @property {string} method HTTP request method
|
||||
* @property {string} url URL String
|
||||
* @property {RouterHandler[]} handlers Array of handler functions
|
||||
*/
|
||||
export type Route<TEnv, TExt> = {
|
||||
method: string
|
||||
url: string
|
||||
handlers: RouterHandler<TEnv, TExt>[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Router Context
|
||||
*
|
||||
* @typedef RouterContext
|
||||
* @property {RouterEnv} env Environment
|
||||
* @property {RouterRequest} req Request Object
|
||||
* @property {RouterResponse} res Response Object
|
||||
* @property {RouterNext} next Next Handler
|
||||
*/
|
||||
export interface RouterContext {
|
||||
env: any
|
||||
req: RouterRequest
|
||||
res: RouterResponse
|
||||
next: RouterNext
|
||||
* Router Context
|
||||
*
|
||||
* @typedef RouterContext
|
||||
* @property {RouterEnv} env Environment
|
||||
* @property {RouterRequest} req Request Object
|
||||
* @property {ExecutionContext} ctx Context Object
|
||||
*/
|
||||
export type RouterContext<TEnv = any, TExt = any> = {
|
||||
env: TEnv
|
||||
req: RouterRequest<TExt>
|
||||
dbg: boolean
|
||||
ctx?: ExecutionContext
|
||||
}
|
||||
|
||||
/**
|
||||
* Request Object
|
||||
*
|
||||
* @typedef RouterRequest
|
||||
* @property {string} url URL
|
||||
* @property {string} method HTTP request method
|
||||
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
||||
* @property {RouterRequestQuery} query Object containing all query parameters
|
||||
* @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 {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
|
||||
*/
|
||||
export interface RouterRequest {
|
||||
url: string
|
||||
method: string
|
||||
params: RouterRequestParams
|
||||
query: RouterRequestQuery
|
||||
headers: Headers
|
||||
body: string | any
|
||||
cf?: IncomingRequestCfProperties
|
||||
[key: string]: any
|
||||
* Request Object
|
||||
*
|
||||
* @typedef RouterRequest
|
||||
* @property {string} url URL
|
||||
* @property {string} method HTTP request method
|
||||
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
||||
* @property {RouterRequestQuery} query Object containing all query parameters
|
||||
* @property {Headers} headers Request headers object
|
||||
* @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
|
||||
*/
|
||||
export type RouterRequest<TExt> = {
|
||||
url: string
|
||||
method: string
|
||||
params: RouterRequestParams
|
||||
query: RouterRequestQuery
|
||||
headers: Headers
|
||||
raw: Request
|
||||
arrayBuffer(): Promise<ArrayBuffer>
|
||||
text(): Promise<string>
|
||||
json<T>(): Promise<T>
|
||||
formData(): Promise<FormData>
|
||||
blob(): Promise<Blob>
|
||||
bearer: () => string
|
||||
cf?: IncomingRequestCfProperties
|
||||
} & TExt
|
||||
|
||||
/**
|
||||
* Request Parameters
|
||||
*
|
||||
* @typedef RouterRequestParams
|
||||
*/
|
||||
export type RouterRequestParams = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Request Parameters
|
||||
*
|
||||
* @typedef RouterRequestParams
|
||||
*/
|
||||
export interface RouterRequestParams {
|
||||
[key: string]: string
|
||||
* Request Query
|
||||
*
|
||||
* @typedef RouterRequestQuery
|
||||
*/
|
||||
export type RouterRequestQuery = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Request Query
|
||||
*
|
||||
* @typedef RouterRequestQuery
|
||||
*/
|
||||
export interface RouterRequestQuery {
|
||||
[key: string]: string
|
||||
* Handler Function
|
||||
*
|
||||
* @callback RouterHandler
|
||||
* @param {RouterContext} ctx
|
||||
* @returns {Promise<Response | void> Response | void}
|
||||
*/
|
||||
export type RouterHandler<TEnv = any, TExt = any> = {
|
||||
(ctx: RouterContext<TEnv, TExt>): Promise<Response | void> | Response | void
|
||||
}
|
||||
|
||||
/**
|
||||
* Response Object
|
||||
*
|
||||
* @typedef RouterResponse
|
||||
* @property {Headers} headers Response headers object
|
||||
* @property {number} [status=204] Return status code (default: `204`)
|
||||
* @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 RouterResponse {
|
||||
headers: Headers
|
||||
status?: number
|
||||
body?: string | any
|
||||
raw?: Response,
|
||||
webSocket?: WebSocket
|
||||
* 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 type RouterCorsConfig = {
|
||||
allowOrigin?: string
|
||||
allowMethods?: string
|
||||
allowHeaders?: string
|
||||
maxAge?: number
|
||||
optionsSuccessStatus?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Next Function
|
||||
*
|
||||
* @callback RouterNext
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export interface RouterNext {
|
||||
(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
allowOrigin?: string
|
||||
allowMethods?: string
|
||||
allowHeaders?: string
|
||||
maxAge?: number
|
||||
optionsSuccessStatus?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Router
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
*/
|
||||
export default class Router {
|
||||
|
||||
/**
|
||||
* Router Array
|
||||
*
|
||||
* @protected
|
||||
* @type {Route[]}
|
||||
*/
|
||||
protected routes: Route[] = []
|
||||
|
||||
/**
|
||||
* Global Handlers
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterHandler[]}
|
||||
*/
|
||||
protected globalHandlers: RouterHandler[] = []
|
||||
|
||||
/**
|
||||
* Debug Mode
|
||||
*
|
||||
* @protected
|
||||
* @type {boolean}
|
||||
*/
|
||||
protected debugMode: boolean = false
|
||||
|
||||
/**
|
||||
* CORS Config
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterCorsConfig}
|
||||
*/
|
||||
protected corsConfig: RouterCorsConfig = {}
|
||||
|
||||
/**
|
||||
* Register global handlers
|
||||
*
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public use(...handlers: RouterHandler[]): Router {
|
||||
for (let handler of handlers) {
|
||||
this.globalHandlers.push(handler)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Register CONNECT route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public connect(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('CONNECT', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register DELETE route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public delete(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('DELETE', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register GET route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public get(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('GET', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register HEAD route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public head(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('HEAD', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register OPTIONS route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public options(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('OPTIONS', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register PATCH route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public patch(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('PATCH', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register POST route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public post(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('POST', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register PUT route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public put(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('PUT', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register TRACE route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public trace(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('TRACE', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register route, ignoring method
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public any(url: string, ...handlers: RouterHandler[]): Router {
|
||||
return this.register('*', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug Mode
|
||||
*
|
||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||
* @returns {Router}
|
||||
*/
|
||||
public debug(state: boolean = true): Router {
|
||||
this.debugMode = state
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable CORS support
|
||||
*
|
||||
* @param {RouterCorsConfig} [config]
|
||||
* @returns {Router}
|
||||
*/
|
||||
public cors(config?: RouterCorsConfig): Router {
|
||||
this.corsConfig = {
|
||||
allowOrigin: config?.allowOrigin || '*',
|
||||
allowMethods: config?.allowMethods || '*',
|
||||
allowHeaders: config?.allowHeaders || '*, Authorization',
|
||||
maxAge: config?.maxAge || 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Register route
|
||||
*
|
||||
* @private
|
||||
* @param {string} method HTTP request method
|
||||
* @param {string} url URL String
|
||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||
* @returns {Router}
|
||||
*/
|
||||
private register(method: string, url: string, handlers: RouterHandler[]): Router {
|
||||
this.routes.push({
|
||||
method,
|
||||
url,
|
||||
handlers
|
||||
})
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Route by request
|
||||
*
|
||||
* @private
|
||||
* @param {RouterRequest} request
|
||||
* @returns {Route | undefined}
|
||||
*/
|
||||
private getRoute(request: RouterRequest): Route | undefined {
|
||||
const url = new URL(request.url)
|
||||
const pathArr = url.pathname.split('/').filter(i => i)
|
||||
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
|
||||
*
|
||||
* @param {any} env
|
||||
* @param {Request} request
|
||||
* @param {any} [extend]
|
||||
* @returns {Response}
|
||||
*/
|
||||
public async handle(env: any, request: Request, extend: any = {}) {
|
||||
try {
|
||||
const req: RouterRequest = {
|
||||
...extend,
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
url: request.url,
|
||||
cf: request.cf,
|
||||
params: {},
|
||||
query: {},
|
||||
body: ''
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
|
||||
if (this.corsConfig.allowOrigin)
|
||||
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||
if (this.corsConfig.allowMethods)
|
||||
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 (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers,
|
||||
status: this.corsConfig.optionsSuccessStatus
|
||||
})
|
||||
}
|
||||
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
||||
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
|
||||
try {
|
||||
req.body = await request.json()
|
||||
} catch {
|
||||
req.body = {}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
req.body = await request.text()
|
||||
} catch {
|
||||
req.body = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
const route = this.getRoute(req)
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
const res: RouterResponse = { headers }
|
||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||
let prevIndex = -1
|
||||
const runner = async (index: number) => {
|
||||
if (index === prevIndex)
|
||||
throw new Error('next() called multiple times')
|
||||
prevIndex = index
|
||||
if (typeof handlers[index] === 'function')
|
||||
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
|
||||
}
|
||||
await runner(0)
|
||||
if (typeof res.body === 'object') {
|
||||
if (!res.headers.has('Content-Type'))
|
||||
res.headers.set('Content-Type', 'application/json')
|
||||
res.body = JSON.stringify(res.body)
|
||||
}
|
||||
if (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 })
|
||||
} catch(err) {
|
||||
console.error(err)
|
||||
return new Response(this.debugMode && err instanceof Error ? err.stack : '', { status: 500 })
|
||||
}
|
||||
}
|
||||
* Router
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
*/
|
||||
export class Router<TEnv = any, TExt = any> {
|
||||
|
||||
/**
|
||||
* Router Array
|
||||
*
|
||||
* @protected
|
||||
* @type {Route[]}
|
||||
*/
|
||||
protected routes: Route<TEnv, TExt>[] = []
|
||||
|
||||
/**
|
||||
* Global Handlers
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterHandler[]}
|
||||
*/
|
||||
protected globalHandlers: RouterHandler<TEnv, TExt>[] = []
|
||||
|
||||
/**
|
||||
* Debug Mode
|
||||
*
|
||||
* @protected
|
||||
* @type {boolean}
|
||||
*/
|
||||
protected debugMode: boolean = false
|
||||
|
||||
/**
|
||||
* CORS Config
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterCorsConfig}
|
||||
*/
|
||||
protected corsConfig: RouterCorsConfig = {}
|
||||
|
||||
/**
|
||||
* CORS enabled
|
||||
*
|
||||
* @protected
|
||||
* @type {boolean}
|
||||
*/
|
||||
protected corsEnabled: boolean = false
|
||||
|
||||
/**
|
||||
* Register global handlers
|
||||
*
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public use(...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
for (let handler of handlers) {
|
||||
this.globalHandlers.push(handler)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Register CONNECT route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public connect(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('CONNECT', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register DELETE route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public delete(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('DELETE', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register GET route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public get(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('GET', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register HEAD route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public head(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('HEAD', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register OPTIONS route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public options(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('OPTIONS', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register PATCH route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public patch(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('PATCH', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register POST route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public post(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('POST', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register PUT route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public put(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('PUT', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register TRACE route
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public trace(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('TRACE', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register route, ignoring method
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @returns {Router}
|
||||
*/
|
||||
public any(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
return this.register('*', url, handlers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug Mode
|
||||
*
|
||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||
* @returns {Router}
|
||||
*/
|
||||
public debug(state: boolean = true): Router<TEnv, TExt> {
|
||||
this.debugMode = state
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable CORS support
|
||||
*
|
||||
* @param {RouterCorsConfig} [config]
|
||||
* @returns {Router}
|
||||
*/
|
||||
public cors(config?: RouterCorsConfig): Router<TEnv, TExt> {
|
||||
this.corsEnabled = true
|
||||
this.corsConfig = {
|
||||
allowOrigin: config?.allowOrigin ?? '*',
|
||||
allowMethods: config?.allowMethods ?? '*',
|
||||
allowHeaders: config?.allowHeaders ?? '*',
|
||||
maxAge: config?.maxAge ?? 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
private setCorsHeaders(headers: Headers = new Headers()): Headers {
|
||||
if (this.corsConfig.allowOrigin && !headers.has('Access-Control-Allow-Origin'))
|
||||
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||
if (this.corsConfig.allowMethods && !headers.has('Access-Control-Allow-Methods'))
|
||||
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||
if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
|
||||
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||
if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
|
||||
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||
return headers
|
||||
}
|
||||
|
||||
/**
|
||||
* Register route
|
||||
*
|
||||
* @private
|
||||
* @param {string} method HTTP request method
|
||||
* @param {string} url URL String
|
||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||
* @returns {Router}
|
||||
*/
|
||||
private register(method: string, url: string, handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
|
||||
this.routes.push({
|
||||
method,
|
||||
url,
|
||||
handlers
|
||||
})
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Route by request
|
||||
*
|
||||
* @private
|
||||
* @param {RouterRequest} request
|
||||
* @returns {Route | undefined}
|
||||
*/
|
||||
private getRoute(request: RouterRequest<TExt>): Route<TEnv, TExt> | undefined {
|
||||
const url = new URL(request.url)
|
||||
const pathArr = url.pathname.split('/').filter(i => i)
|
||||
|
||||
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
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {TEnv} env
|
||||
* @param {TExt} [ext]
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, ext?: TExt): Promise<Response> {
|
||||
const req = {
|
||||
...(ext ?? {}),
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
url: request.url,
|
||||
cf: request.cf,
|
||||
raw: request,
|
||||
params: {},
|
||||
query: {},
|
||||
arrayBuffer: request.arrayBuffer,
|
||||
text: request.text,
|
||||
json: <T>(): Promise<T> => request.json<T>(),
|
||||
formData: request.formData,
|
||||
blob: request.blob,
|
||||
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim() ?? '',
|
||||
} as RouterRequest<TExt>
|
||||
|
||||
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: this.setCorsHeaders(),
|
||||
status: this.corsConfig.optionsSuccessStatus
|
||||
})
|
||||
}
|
||||
|
||||
const route = this.getRoute(req)
|
||||
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
|
||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||
const dbg = this.debugMode
|
||||
|
||||
let response: Response | undefined
|
||||
|
||||
for (const handler of handlers) {
|
||||
const res = await handler({ env, req, dbg, 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,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"preserveConstEnums": true,
|
||||
|
||||
Reference in New Issue
Block a user