1
0

97 Commits

Author SHA1 Message Date
a4fd646d6b remove connect and trace methods 2024-01-20 02:15:34 +01:00
606d5f1cb2 clean up 2023-11-16 22:38:51 +01:00
95ccb2263a 3.1.3 2023-11-14 14:54:46 +01:00
dc88d900cb fix default extension types 2023-11-14 14:54:04 +01:00
0dca90f4f9 3.1.2 2023-11-12 18:52:30 +01:00
cb8724edc4 clean up 2023-11-12 18:48:49 +01:00
08c329ff20 3.1.1 2023-10-31 16:45:35 +01:00
e9a0a2436d use body multiple times 2023-10-31 16:45:31 +01:00
76d7040a1b 3.1.0 2023-09-29 12:20:50 +02:00
0037fb64ea update readme 2023-09-29 12:20:23 +02:00
Toby
a5ccf0fc01 support Access-Control-Allow-Credentials and vary CORS headers, thanks @akreiling 2023-09-29 10:14:07 +00:00
Toby
e006d0a3b1 use a new buffer for every invocation of handle, thanks @akreiling 2023-09-29 10:12:15 +00:00
Andrew Kreiling
c7d7a642e6 support Access-Control-Allow-Credentials and vary CORS headers 2023-09-28 07:52:34 -05:00
Andrew Kreiling
49c7897bd0 use a new buffer for every invocation of handle 2023-09-28 07:52:14 -05:00
e28976a4b6 update migration 2023-08-22 21:04:44 +02:00
eea9e580f6 3.0.0 2023-08-19 18:10:11 +02:00
68e614b3fa prepare workflow for release 2023-08-19 18:00:13 +02:00
7a20454f79 update dependencies 2023-08-19 17:55:53 +02:00
101de4f5f6 3.0.0-16 2023-05-25 20:38:48 +02:00
9ee1182fa9 update node for dev 2023-05-25 20:37:41 +02:00
0309b0131f update migration guide 2023-05-25 20:34:55 +02:00
afd7ea662f 3.0.0-15 2023-05-25 20:01:45 +02:00
a742753cb7 update workflow 2023-05-25 20:01:36 +02:00
d631645b99 3.0.0-14 2023-05-25 19:55:37 +02:00
cb1bf98053 update types 2023-05-25 19:55:25 +02:00
648514a3c7 3.0.0-13 2023-05-25 19:52:56 +02:00
34f4512dee allow for context extension 2023-05-25 19:52:31 +02:00
02b65e85e6 clean up 2023-05-25 17:35:11 +02:00
d71b0638c4 3.0.0-12 2023-03-15 22:04:06 +01:00
0c7f04d71b make body reusable 2023-03-15 22:04:06 +01:00
c18e164018 update dependencies 2023-03-15 01:31:33 +01:00
307a93d86c 3.0.0-11 2023-02-21 15:45:20 +01:00
3a955af1bc fix cors edge case 2023-02-21 15:45:12 +01:00
db22422968 add arrayBuffer, text, formData, blob 2023-02-21 15:44:49 +01:00
0a73e4c32e 3.0.0-10 2023-02-05 02:11:19 +01:00
8bd8e50ee5 update 2023-02-05 02:11:09 +01:00
e4ec06bf47 3.0.0-9 2023-02-05 01:46:53 +01:00
2ad75dc3fb move things around, update body behavior 2023-02-05 01:46:20 +01:00
c2b6189a86 3.0.0-8 2023-02-02 20:53:11 +01:00
33cafbf17c update replace to be case insensitive 2023-02-02 20:53:02 +01:00
1e78778ba0 3.0.0-7 2023-02-02 20:38:45 +01:00
b0d05656bb add bearer helper function 2023-02-02 20:37:58 +01:00
d4ba12a517 update readme 2023-02-02 19:03:18 +01:00
b48e5c2333 clean up 2023-02-02 18:51:12 +01:00
bf41e2c193 update readme 2023-02-02 18:48:20 +01:00
5342cfd310 update dev dependencies 2023-02-02 18:43:36 +01:00
8f400ff5b7 3.0.0-6 2023-02-02 18:38:37 +01:00
51f30f642f clean up 2023-02-02 18:37:45 +01:00
bcab122e15 add dbg to handler context 2023-02-02 18:37:28 +01:00
f3181ca9a5 change || to ?? 2023-02-02 18:31:33 +01:00
7edfc835fa change interfaces to types 2023-02-02 18:30:03 +01:00
7300e36469 update migration guide 2023-02-02 18:08:49 +01:00
e122feadb5 update readmes 2023-02-02 17:40:28 +01:00
ceed474f24 3.0.0-5 2023-01-16 21:27:11 +01:00
864b7f153c extend request type 2023-01-16 21:26:42 +01:00
6a2173cdbc 3.0.0-4 2022-11-28 23:09:34 +01:00
87a3d344d9 add req.raw type 2022-11-28 23:09:12 +01:00
9f96fd112e 3.0.0-3 2022-11-28 23:04:30 +01:00
5f34e30c1e add raw request 2022-11-28 23:04:12 +01:00
b38baf7d62 add editorconfig 2022-11-28 23:03:59 +01:00
07cb83ff9f 3.0.0-2 2022-11-28 21:27:49 +01:00
2a064dcb9c make cf ctx optional 2022-11-28 21:27:25 +01:00
5e18d06dfd 3.0.0-1 2022-11-28 20:34:54 +01:00
4f169120de update workflow 2022-11-28 20:33:18 +01:00
eeb1b69e62 3.0.0-0 2022-11-28 20:09:35 +01:00
a80cf9ea2e recalculate file size 2022-11-25 01:15:35 +01:00
c41e3e95f9 clean up 2022-11-25 01:13:22 +01:00
61ad67766f switch to return syntax 2022-11-25 01:13:22 +01:00
c6dfaa3158 add editorconfig 2022-11-25 01:13:22 +01:00
215a3731da switch to return syntax 2022-11-25 01:10:51 +01:00
ad4557ecb3 add editorconfig 2022-11-25 00:58:21 +01:00
2529e5ce24 2.3.0 2022-11-25 00:43:43 +01:00
42de017ba0 update readme 2022-11-25 00:41:41 +01:00
81dd03af27 ocd 2022-11-24 23:33:48 +01:00
7fe0a5405f at least a little bit nicer 2022-11-24 23:13:30 +01:00
Toby
05984eb7da Update README.md 2022-11-24 19:28:11 +01:00
Toby
ba371dcc6d Update README.md 2022-11-24 19:27:10 +01:00
Toby
aeb4eb06e4 add TEnv generic 2022-11-24 17:37:52 +01:00
efd74609f1 add default any 2022-11-24 17:36:33 +01:00
Toby
fbc862a1f0 Merge branch 'main' into env-type-support 2022-11-24 17:34:33 +01:00
01487748af update readme 2022-11-24 17:32:11 +01:00
Toby
3374b92075 Update README.md 2022-11-24 17:32:11 +01:00
e8212b5fa8 rename T to TEnv 2022-11-24 16:02:17 +01:00
Toby
ded6b81e28 Update README.md 2022-11-24 15:50:10 +01:00
Anbcodes
972dc916f7 added the ability to specify the type of RouterContext.env 2022-10-06 15:57:18 -04:00
d3b86f1dbe 2.2.0 2022-10-03 00:34:06 +02:00
aadb398b48 drop default export 2022-10-03 00:32:54 +02:00
5fa3475a20 2.1.2 2022-10-03 00:13:59 +02:00
0637549e90 remove compatibility box 2022-10-03 00:13:51 +02:00
f3279e71fc typo fix 2022-10-03 00:09:03 +02:00
bdb7be3699 2.1.1 2022-10-03 00:02:21 +02:00
45a781ea66 clean up 2022-10-03 00:01:13 +02:00
7f44f304a2 remove explicit authorization header 2022-10-02 23:57:52 +02:00
a786262ec6 fix cors 2022-10-02 23:50:48 +02:00
8e58dc349e 2.1.0 2022-09-29 18:56:02 +02:00
e94e84a742 fix cors always on issue 2022-09-29 18:48:23 +02:00
b16a56bbca minor type fixes 2022-07-19 18:51:31 +02:00
10 changed files with 770 additions and 615 deletions

13
.editorconfig Normal file
View File

@@ -0,0 +1,13 @@
root = true
[*]
end_of_line = lf
insert_final_newline = false
[src/**.ts]
charset = utf-8
indent_style = tab
[README.md]
indent_style = space
indent_size = 4

View File

@@ -11,7 +11,7 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 16 node-version: latest
registry-url: https://registry.npmjs.org/ registry-url: https://registry.npmjs.org/
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
@@ -21,10 +21,11 @@ jobs:
env: env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
run: npm publish --tag latest --access public run: npm publish --tag latest --access public
- uses: actions/setup-node@v1 - uses: actions/setup-node@v3
with: with:
node-version: latest
registry-url: https://npm.pkg.github.com/ registry-url: https://npm.pkg.github.com/
- name: Publish to GPR - name: Publish to GPR
env: env:
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
run: npm publish --tag latest --access public run: npm publish --tag latest --access public

View File

@@ -3,4 +3,5 @@ src/
test/ test/
.nvmrc .nvmrc
MIGRATION.md MIGRATION.md
tsconfig.json tsconfig.json
.editorconfig

1
.nvmrc
View File

@@ -1 +0,0 @@
v16

View File

@@ -1,71 +1,69 @@
# Migration Guide # Migration Guide
From `v1.x.x` to `v2.x.x`. From `v2.x.x` to `v3.x.x`.
## Contents ## Contents
- [Preparation](#preparation) - [Update Router](#update-router)
- [Update](#update) - [Handlers](#handlers)
- [Import / Require](#import--require)
- [Routes](#routes)
- [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 to the latest version version of the router.
## Update
Update to the latest version verstion
```bash ```bash
npm i -D @tsndr/cloudflare-worker-router npm i -D @tsndr/cloudflare-worker-router@^3
``` ```
## 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 ### Before
```javascript ```typescript
const Router = require('@tsndr/cloudflare-worker-router') // 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 ### After
```javascript ```typescript
import Router from '@tsndr/cloudflare-worker-router' // 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>

369
README.md
View File

@@ -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,184 @@ 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) - [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 ## Usage
### Simple Example Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
```javascript ### TypeScript Example
import Router from '@tsndr/cloudflare-worker-router'
// Initialize router ```typescript
const router = new Router() import { Router } from '@tsndr/cloudflare-worker-router'
// Enabling buildin CORS support // Env Types
export type Var<T = string> = T
export type Secret<T = string> = T
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
ENVIRONMENT: Var<'dev' | 'prod'>
SECRET_TOKEN: Secret
}
// Request Extension
export type ExtReq = {
userId?: number
}
// Context Extension
export type ExtCtx = {
//sentry?: Toucan
}
// Initialize Router
const router = new Router<Env, ExtCtx, ExtReq>()
// Enabling build in CORS support
router.cors() router.cors()
// Register global middleware // Register global middleware
router.use(({ req, res, next }) => { router.use(({ env, req }) => {
res.headers.set('X-Global-Middlewares', 'true') // Intercept if token doesn't match
next() if (req.headers.get('authorization') !== env.SECRET_TOKEN)
return new Response(null, { status: 401 })
}) })
// 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 }) => {
if (req.headers.get('authorization') === env.SECRET_TOKEN)
return new Response(null, { status: 401 })
if (!apiTokenIsCorrect) { }, ({ req }) => {
res.status = 401
return
}
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(({ 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 ## Reference
@@ -96,6 +199,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 +213,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])`
@@ -117,25 +226,30 @@ If enabled will overwrite other `OPTIONS` requests.
#### `config` (object, optional) #### `config` (object, optional)
Key | Type | Default Value Key | Type | Default Value
---------------------- | --------- | ------------- -------------------------- | ---------- | -------------
`allowOrigin` | `string` | `*` `allowOrigin` | `string` | `*`
`allowMethods` | `string` | `*` `allowMethods` | `string` | `*`
`allowHeaders` | `string` | `*` `allowHeaders` | `string` | `*`
`maxAge` | `integer` | `86400` `allowCredentials` | `boolean` | `undefined`
`optionsSuccessStatus` | `integer` | `204` `vary` | `string` | `undefined`
`maxAge` | `integer` | `86400`
`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 +259,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 +282,132 @@ Key | Type | Description
`query` | `object` | Object containing all query parameters `query` | `object` | Object containing all query parameters
### `res`-Object ## Getting started
Key | Type | Description Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
----------- | ------------------- | -----------
`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 #### Initialize Project
--- ```bash
### ❗️ Compatibility ❗️ wrangler init <name>
```
CLI Tool | Router Use of TypeScript is strongly encouraged :)
-------- | ------
[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
```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 { // Env Types
export type Var<T = string> = T
export type Secret<T = string> = T
export type 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
//
// Example Variable
// ENVIRONMENT: Var<'dev' | 'prod'>
//
// Example Secret
// JWT_SECRET: Secret
} }
const router = new Router() // Request Extension
export type ExtReq = {
userId?: number
}
// Context Extension
export type ExtCtx = {
//sentry?: Toucan
}
// Handler Type
export type Handler = RouterHandler<Env, ExtCtx, ExtReq>
// Initialize Router
const router = new Router<Env, ExtCtx, ExtReq>()
// Enable Debug Mode
router.debug()
// Enabling build in CORS support
//router.cors()
/// Example Route
//
// router.get('/hi', async () => {
// return new Response('Hello World')
// })
/// Example Route for splitting into multiple files
//
// const helloHandler: Handler = async () => {
// return new Response('Hello World')
// }
//
// router.get('/hellow', helloHandler)
// 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()
// Enable Debug Mode
//router.debug()
// Enabling build in CORS support
//router.cors()
/// 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 // 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>

38
package-lock.json generated
View File

@@ -1,50 +1,36 @@
{ {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "2.0.2", "version": "3.1.3",
"lockfileVersion": 2, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "2.0.2", "version": "3.1.3",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^4.20231025.0",
"typescript": "^4.7.4" "typescript": "^5.2.2"
} }
}, },
"node_modules/@cloudflare/workers-types": { "node_modules/@cloudflare/workers-types": {
"version": "3.13.0", "version": "4.20231025.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz", "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20231025.0.tgz",
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==", "integrity": "sha512-TkcZkntUTOcvJ4vgmwpNfLTclpMbmbClZCe62B25/VTukmyv91joRa4eKzSjzCZUXTbFHNmVdOpmGaaJU2U3+A==",
"dev": true "dev": true
}, },
"node_modules/typescript": { "node_modules/typescript": {
"version": "4.7.4", "version": "5.2.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz",
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==",
"dev": true, "dev": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
}, },
"engines": { "engines": {
"node": ">=4.2.0" "node": ">=14.17"
} }
} }
},
"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==",
"dev": true
},
"typescript": {
"version": "4.7.4",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz",
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==",
"dev": true
}
} }
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "2.0.2", "version": "3.1.3",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
@@ -31,7 +31,7 @@
}, },
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme", "homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^4.20231025.0",
"typescript": "^4.7.4" "typescript": "^5.2.2"
} }
} }

View File

@@ -1,450 +1,445 @@
/** /**
* 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 type Route<Env, CtxExt, ReqExt> = {
method: string method: string
url: string url: string
handlers: RouterHandler[] handlers: RouterHandler<Env, CtxExt, ReqExt>[]
} }
/** /**
* Router Context * Router Context
* *
* @typedef RouterContext * @typedef RouterContext
* @property {Object<string, string>} env Environment * @property {RouterEnv} env Environment
* @property {RouterRequest} req Request Object * @property {RouterRequest} req Request Object
* @property {RouterResponse} res Response Object * @property {ExecutionContext} ctx Context Object
* @property {RouterNext} next Next Handler */
*/ export type RouterContext<Env = any, CtxExt = {}, ReqExt = {}> = CtxExt & {
export interface RouterContext { env: Env
env: any req: RouterRequest<ReqExt>
req: RouterRequest dbg: boolean
res: RouterResponse ctx?: ExecutionContext
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 {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 {Request} raw Raw Request Object
* @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 type RouterRequest<ReqExt> = ReqExt & {
url: string url: string
method: string method: string
params: RouterRequestParams params: RouterRequestParams
query: RouterRequestQuery query: RouterRequestQuery
headers: Headers headers: Headers
body: any raw: Request
cf?: IncomingRequestCfProperties arrayBuffer(): Promise<ArrayBuffer>
[key: string]: any text(): Promise<string>
json<T>(): Promise<T>
formData(): Promise<FormData>
blob(): Promise<Blob>
bearer(): string | undefined
cf?: IncomingRequestCfProperties
} }
/** /**
* Request Parameters * Request Parameters
* *
* @typedef RouterRequestParams * @typedef RouterRequestParams
*/ */
export interface RouterRequestParams { export type RouterRequestParams = {
[key: string]: string [key: string]: string
} }
/** /**
* Request Query * Request Query
* *
* @typedef RouterRequestQuery * @typedef RouterRequestQuery
*/ */
export interface RouterRequestQuery { export type 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 {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 type RouterHandler<Env = any, CtxExt = {}, ReqExt = {}> = {
*/ (ctx: RouterContext<Env, CtxExt, ReqExt>): Promise<Response | void> | Response | void
export interface RouterResponse {
headers: Headers
status?: number
body?: any
raw?: Response,
webSocket?: WebSocket
} }
/** /**
* Next Function * CORS Config
* *
* @callback RouterNext * @typedef RouterCorsConfig
* @returns {Promise} * @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 {boolean} [allowCredentials="true"] Access-Control-Allow-Credentials (default: undefined)
* @property {string} [vary="origin"] vary (default: undefined)
* @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
allowCredentials?: boolean
vary?: string
maxAge?: number
optionsSuccessStatus?: number
}
export type RouterBuffer = {
arrayBuffer?: ArrayBuffer
text?: string
json?: any
formData?: FormData
blob?: Blob
} }
/** /**
* Handler Function * Router
* *
* @callback RouterHandler * @public
* @param {RouterContext} ctx * @class
* @returns {Promise<void> | void} */
*/ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
export interface RouterHandler {
(ctx: RouterContext): Promise<void> | void /**
} * Router Array
*
/** * @protected
* CORS Config * @type {Route[]}
* */
* @typedef RouterCorsConfig protected routes: Route<Env, CtxExt, ReqExt>[] = []
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`) /**
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`) * Global Handlers
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`) *
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`) * @protected
*/ * @type {RouterHandler[]}
export interface RouterCorsConfig { */
allowOrigin: string protected globalHandlers: RouterHandler<Env, CtxExt, ReqExt>[] = []
allowMethods: string
allowHeaders: string /**
maxAge: number * Debug Mode
optionsSuccessStatus: number *
} * @protected
* @type {boolean}
/** */
* Router protected debugMode: boolean = false
*
* @public /**
* @class * CORS Config
*/ *
export default class Router { * @protected
* @type {RouterCorsConfig}
/** */
* Router Array protected corsConfig: RouterCorsConfig = {}
*
* @protected /**
* @type {Route[]} * CORS enabled
*/ *
protected routes: Route[] = [] * @protected
* @type {boolean}
/** */
* Global Handlers protected corsEnabled: boolean = false
*/
protected globalHandlers: RouterHandler[] = [] /**
* Register global handlers
/** *
* Debug Mode * @param {RouterHandler[]} handlers
* * @returns {Router}
* @protected */
* @type {boolean} public use(...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ for (let handler of handlers) {
protected debugMode: boolean = false this.globalHandlers.push(handler)
}
/** return this
* CORS Config }
*
* @protected /**
* @type {RouterCorsConfig} * Register DELETE route
*/ *
protected corsConfig: RouterCorsConfig = { * @param {string} url
allowOrigin: '*', * @param {RouterHandler[]} handlers
allowMethods: '*', * @returns {Router}
allowHeaders: '*', */
maxAge: 86400, public delete(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
optionsSuccessStatus: 204 return this.register('DELETE', url, handlers)
} }
/** /**
* Register global handlers * Register GET route
* *
* @param {RouterHandler[]} handlers * @param {string} url
* @returns {Router} * @param {RouterHandler[]} handlers
*/ * @returns {Router}
public use(...handlers: RouterHandler[]): Router { */
for (let handler of handlers) { public get(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
this.globalHandlers.push(handler) return this.register('GET', url, handlers)
} }
return this
} /**
* Register HEAD route
/** *
* Register CONNECT route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public head(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('HEAD', url, handlers)
public connect(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('CONNECT', url, handlers)
} /**
* Register OPTIONS route
/** *
* Register DELETE route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public options(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('OPTIONS', url, handlers)
public delete(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('DELETE', url, handlers)
} /**
* Register PATCH route
/** *
* Register GET route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public patch(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('PATCH', url, handlers)
public get(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('GET', url, handlers)
} /**
* Register POST route
/** *
* Register HEAD route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public post(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('POST', url, handlers)
public head(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('HEAD', url, handlers)
} /**
* Register PUT route
/** *
* Register OPTIONS route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public put(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('PUT', url, handlers)
public options(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('OPTIONS', url, handlers)
} /**
* Register route, ignoring method
/** *
* Register PATCH route * @param {string} url
* * @param {RouterHandler[]} handlers
* @param {string} url * @returns {Router}
* @param {RouterHandler[]} handlers */
* @returns {Router} public any(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
*/ return this.register('*', url, handlers)
public patch(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('PATCH', url, handlers)
} /**
* Debug Mode
/** *
* Register POST route * @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
* * @returns {Router}
* @param {string} url */
* @param {RouterHandler[]} handlers public debug(state: boolean = true): Router<Env, CtxExt, ReqExt> {
* @returns {Router} this.debugMode = state
*/ return this
public post(url: string, ...handlers: RouterHandler[]): Router { }
return this.register('POST', url, handlers)
} /**
* Enable CORS support
/** *
* Register PUT route * @param {RouterCorsConfig} [config]
* * @returns {Router}
* @param {string} url */
* @param {RouterHandler[]} handlers public cors(config?: RouterCorsConfig): Router<Env, CtxExt, ReqExt> {
* @returns {Router} this.corsEnabled = true
*/ this.corsConfig = {
public put(url: string, ...handlers: RouterHandler[]): Router { allowOrigin: config?.allowOrigin ?? '*',
return this.register('PUT', url, handlers) allowMethods: config?.allowMethods ?? '*',
} allowHeaders: config?.allowHeaders ?? '*',
allowCredentials: config?.allowCredentials ?? undefined,
/** vary: config?.vary ?? undefined,
* Register TRACE route maxAge: config?.maxAge ?? 86400,
* optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
* @param {string} url }
* @param {RouterHandler[]} handlers return this
* @returns {Router} }
*/
public trace(url: string, ...handlers: RouterHandler[]): Router { private setCorsHeaders(headers: Headers = new Headers()): Headers {
return this.register('TRACE', url, handlers) 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)
* Register route, ignoring method if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
* headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
* @param {string} url if (this.corsConfig.allowCredentials && !headers.has('Access-Control-Allow-Credentials'))
* @param {RouterHandler[]} handlers headers.set('Access-Control-Allow-Credentials', this.corsConfig.allowCredentials.toString())
* @returns {Router} if (this.corsConfig.vary && !headers.has('vary'))
*/ headers.set('vary', this.corsConfig.vary.toString())
public any(url: string, ...handlers: RouterHandler[]): Router { if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
return this.register('*', url, handlers) headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
} return headers
}
/**
* Debug Mode /**
* * Register route
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true) *
* @returns {Router} * @private
*/ * @param {string} method HTTP request method
public debug(state = true): Router { * @param {string} url URL String
this.debugMode = state * @param {RouterHandler[]} handlers Arrar of handler functions
return this * @returns {Router}
} */
private register(method: string, url: string, handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
/** this.routes.push({
* Enable CORS support method,
* url,
* @param {RouterCorsConfig} [config] handlers
* @returns {Router} })
*/
public cors(config?: RouterCorsConfig): Router { return this
this.corsConfig = { }
allowOrigin: config?.allowOrigin || '*',
allowMethods: config?.allowMethods || '*', /**
allowHeaders: config?.allowHeaders || '*, Authorization', * Get Route by request
maxAge: config?.maxAge || 86400, *
optionsSuccessStatus: config?.optionsSuccessStatus || 204 * @private
} * @param {RouterRequest} request
return this * @returns {Route | undefined}
} */
private getRoute(request: RouterRequest<ReqExt>): Route<Env, CtxExt, ReqExt> | undefined {
/** const url = new URL(request.url)
* Register route const pathArr = url.pathname.split('/').filter(i => i)
*
* @private return this.routes.find(r => {
* @param {string} method HTTP request method const routeArr = r.url.split('/').filter(i => i)
* @param {string} url URL String
* @param {RouterHandler[]} handlers Arrar of handler functions if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
* @returns {Router} return false
*/
private register(method: string, url: string, handlers: RouterHandler[]): Router { const params: RouterRequestParams = {}
this.routes.push({
method, for (let i = 0; i < routeArr.length; i++) {
url, if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
handlers return false
})
return this if (routeArr[i][0] === ':')
} params[routeArr[i].substring(1)] = pathArr[i]
}
/**
* Get Route by request request.params = params
*
* @private const query: any = {}
* @param {Request} request
* @returns {RouterRequest | undefined} for (const [k, v] of url.searchParams.entries()) {
*/ query[k] = v
private getRoute(request: RouterRequest): Route | undefined { }
const url = new URL(request.url)
const pathArr = url.pathname.split('/').filter(i => i) request.query = query
return this.routes.find(r => {
const routeArr = r.url.split('/').filter(i => i) return true
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length) }) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
return false }
const params: RouterRequestParams = {}
for (let i = 0; i < routeArr.length; i++) { /**
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':') * Handle requests
return false *
if (routeArr[i][0] === ':') * @param {Request} request
params[routeArr[i].substring(1)] = pathArr[i] * @param {Env} env
} * @param {CtxExt} [ctxExt]
request.params = params * @param {ReqExt} [reqExt]
const query: any = {} * @returns {Promise<Response>}
for (const [k, v] of url.searchParams.entries()) { */
query[k] = v public async handle(request: Request, env: Env, ctx?: ExecutionContext, ctxExt?: CtxExt, reqExt?: ReqExt): Promise<Response> {
} const buffer: RouterBuffer = {}
request.query = query const req = {
return true ...(reqExt ?? {}),
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method)) method: request.method,
} headers: request.headers,
url: request.url,
/** cf: request.cf,
* Handle requests raw: request,
* params: {},
* @param {any} env query: {},
* @param {Request} request arrayBuffer: async (): Promise<ArrayBuffer> => buffer.arrayBuffer ? buffer.arrayBuffer : buffer.arrayBuffer = await request.clone().arrayBuffer(),
* @param {any} [extend] text: async (): Promise<string> => buffer.text ? buffer.text : buffer.text = await request.clone().text(),
* @returns {Response} json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
*/ formData: async (): Promise<FormData> => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(),
public async handle(env: any, request: Request, extend: any = {}) { blob: async (): Promise<Blob> => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(),
try { bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
const req: RouterRequest = { } as RouterRequest<ReqExt>
...extend,
method: request.method, if (this.corsEnabled && req.method === 'OPTIONS') {
headers: request.headers, return new Response(null, {
url: request.url, headers: this.setCorsHeaders(),
cf: request.cf, status: this.corsConfig.optionsSuccessStatus
params: {}, })
query: {}, }
body: ''
} const route = this.getRoute(req)
if (req.method === 'OPTIONS' && Object.keys(this.corsConfig).length) {
return new Response(null, { if (!route)
headers: { return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
'Access-Control-Allow-Origin': this.corsConfig.allowOrigin,
'Access-Control-Allow-Methods': this.corsConfig.allowMethods, const handlers = [...this.globalHandlers, ...route.handlers]
'Access-Control-Allow-Headers': this.corsConfig.allowHeaders, const dbg = this.debugMode
'Access-Control-Max-Age': this.corsConfig.maxAge!.toString()
}, let response: Response | undefined
status: this.corsConfig.optionsSuccessStatus
}) for (const handler of handlers) {
} const context = {
if (['POST', 'PUT', 'PATCH'].includes(req.method)) { ...(ctxExt ?? {}),
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) { env,
try { req,
req.body = await request.json() dbg,
} catch { ctx
req.body = {} } as RouterContext<Env, CtxExt, ReqExt>
}
} else { const res = await handler(context)
try {
req.body = await request.text() if (res) {
} catch { response = res
req.body = '' break
} }
} }
}
const route = this.getRoute(req) if (!response)
if (!route) return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
const res: RouterResponse = { headers: new Headers() } if (this.corsEnabled) {
if (Object.keys(this.corsConfig).length) { response = new Response(response.body, response)
res.headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin) this.setCorsHeaders(response.headers)
res.headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods) }
res.headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
res.headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString()) return response
} }
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 })
}
}
} }

View File

@@ -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"]
} }