Compare commits
58 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
95ccb2263a
|
|||
|
dc88d900cb
|
|||
|
0dca90f4f9
|
|||
|
cb8724edc4
|
|||
|
08c329ff20
|
|||
|
e9a0a2436d
|
|||
|
76d7040a1b
|
|||
|
0037fb64ea
|
|||
|
|
a5ccf0fc01 | ||
|
|
e006d0a3b1 | ||
|
|
c7d7a642e6 | ||
|
|
49c7897bd0 | ||
|
e28976a4b6
|
|||
|
eea9e580f6
|
|||
|
68e614b3fa
|
|||
|
7a20454f79
|
|||
|
101de4f5f6
|
|||
|
9ee1182fa9
|
|||
|
0309b0131f
|
|||
|
afd7ea662f
|
|||
|
a742753cb7
|
|||
|
d631645b99
|
|||
|
cb1bf98053
|
|||
|
648514a3c7
|
|||
|
34f4512dee
|
|||
|
02b65e85e6
|
|||
|
d71b0638c4
|
|||
|
0c7f04d71b
|
|||
|
c18e164018
|
|||
|
307a93d86c
|
|||
|
3a955af1bc
|
|||
|
db22422968
|
|||
|
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
|
@@ -7,3 +7,7 @@ insert_final_newline = false
|
|||||||
[src/**.ts]
|
[src/**.ts]
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
|
|
||||||
|
[README.md]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
name: Publish (pre)
|
name: Publish (main)
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
@@ -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
|
||||||
@@ -20,11 +20,12 @@ jobs:
|
|||||||
- name: Publish to npmjs
|
- name: Publish to npmjs
|
||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||||
run: npm publish --tag pre --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 pre --access public
|
run: npm publish --tag latest --access public
|
||||||
@@ -3,4 +3,5 @@ src/
|
|||||||
test/
|
test/
|
||||||
.nvmrc
|
.nvmrc
|
||||||
MIGRATION.md
|
MIGRATION.md
|
||||||
tsconfig.json
|
tsconfig.json
|
||||||
|
.editorconfig
|
||||||
96
MIGRATION.md
96
MIGRATION.md
@@ -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>
|
|
||||||
|
|||||||
159
README.md
159
README.md
@@ -12,7 +12,7 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
|||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
- [Reference](#reference)
|
- [Reference](#reference)
|
||||||
- [Setup](#setup)
|
- [Getting started](#getting-started)
|
||||||
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
@@ -26,12 +26,18 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
|
||||||
|
|
||||||
### TypeScript Example
|
### TypeScript Example
|
||||||
|
|
||||||
```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
|
||||||
//
|
//
|
||||||
@@ -41,22 +47,32 @@ export interface Env {
|
|||||||
// 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
|
||||||
|
|
||||||
SECRET_TOKEN: string
|
ENVIRONMENT: Var<'dev' | 'prod'>
|
||||||
|
|
||||||
|
SECRET_TOKEN: Secret
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize router
|
// Request Extension
|
||||||
const router = new Router<Env>()
|
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
|
// Enabling build in CORS support
|
||||||
router.cors()
|
router.cors()
|
||||||
|
|
||||||
// Register global middleware
|
// Register global middleware
|
||||||
router.use(() => {
|
router.use(({ env, req }) => {
|
||||||
return new Response(null, {
|
// Intercept if token doesn't match
|
||||||
headers: {
|
if (req.headers.get('authorization') !== env.SECRET_TOKEN)
|
||||||
'X-Global-Middlewares': 'true'
|
return new Response(null, { status: 401 })
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Simple get
|
// Simple get
|
||||||
@@ -85,9 +101,7 @@ router.post('/user/:id', ({ req }) => {
|
|||||||
|
|
||||||
// Delete route using a middleware
|
// Delete route using a middleware
|
||||||
router.delete('/user/:id', ({ env, req }) => {
|
router.delete('/user/:id', ({ env, req }) => {
|
||||||
const { SECRET_TOKEN } = env
|
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||||
|
|
||||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
|
||||||
return new Response(null, { status: 401 })
|
return new Response(null, { status: 401 })
|
||||||
|
|
||||||
}, ({ req }) => {
|
}, ({ req }) => {
|
||||||
@@ -121,12 +135,10 @@ const router = new Router()
|
|||||||
router.cors()
|
router.cors()
|
||||||
|
|
||||||
// Register global middleware
|
// Register global middleware
|
||||||
router.use(() => {
|
router.use(({ env, req }) => {
|
||||||
return new Response(null, {
|
// Intercept if token doesn't match
|
||||||
headers: {
|
if (req.headers.get('authorization') !== env.SECRET_TOKEN)
|
||||||
'X-Global-Middlewares': 'true'
|
return new Response(null, { status: 401 })
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Simple get
|
// Simple get
|
||||||
@@ -139,11 +151,12 @@ router.get('/user', () => {
|
|||||||
|
|
||||||
// Post route with url parameter
|
// Post route with url parameter
|
||||||
router.post('/user/:id', ({ req }) => {
|
router.post('/user/:id', ({ req }) => {
|
||||||
|
|
||||||
const userId = req.params.id
|
const userId = req.params.id
|
||||||
|
|
||||||
// Do stuff
|
// Do stuff
|
||||||
|
|
||||||
if (errorDoingStuff) {
|
if (!true) {
|
||||||
return Response.json({
|
return Response.json({
|
||||||
error: 'Error doing stuff!'
|
error: 'Error doing stuff!'
|
||||||
}, { status: 400 })
|
}, { status: 400 })
|
||||||
@@ -154,17 +167,16 @@ router.post('/user/:id', ({ req }) => {
|
|||||||
|
|
||||||
// Delete route using a middleware
|
// Delete route using a middleware
|
||||||
router.delete('/user/:id', ({ env, req }) => {
|
router.delete('/user/:id', ({ env, req }) => {
|
||||||
const { SECRET_TOKEN } = env
|
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||||
|
|
||||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
|
||||||
return new Response(null, { status: 401 })
|
return new Response(null, { status: 401 })
|
||||||
|
|
||||||
}, ({ req }) => {
|
}, ({ req }) => {
|
||||||
const userId = req.params.id
|
|
||||||
|
|
||||||
// Do stuff...
|
const userId = req.params.id
|
||||||
|
|
||||||
return Response.json({ userId })
|
// Do stuff...
|
||||||
|
|
||||||
|
return Response.json({ userId })
|
||||||
})
|
})
|
||||||
|
|
||||||
// Listen Cloudflare Workers Fetch Event
|
// Listen Cloudflare Workers Fetch Event
|
||||||
@@ -214,13 +226,15 @@ 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`
|
||||||
|
|
||||||
|
|
||||||
### Supported Methods
|
### Supported Methods
|
||||||
@@ -268,7 +282,7 @@ Key | Type | Description
|
|||||||
`query` | `object` | Object containing all query parameters
|
`query` | `object` | Object containing all query parameters
|
||||||
|
|
||||||
|
|
||||||
## Setup
|
## Getting started
|
||||||
|
|
||||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
|
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
|
||||||
|
|
||||||
@@ -291,7 +305,11 @@ npm i -D @tsndr/cloudflare-worker-router
|
|||||||
```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
|
||||||
//
|
//
|
||||||
@@ -300,32 +318,57 @@ export interface Env {
|
|||||||
//
|
//
|
||||||
// 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<Env>()
|
// 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
|
/// Example Route
|
||||||
//
|
//
|
||||||
// router.get(/'hi', ({ res }) => {
|
// router.get('/hi', async () => {
|
||||||
// res.body = 'Hello World'
|
// return new Response('Hello World')
|
||||||
//}
|
// })
|
||||||
|
|
||||||
|
|
||||||
/// Example Route for splitting into multiple files
|
/// Example Route for splitting into multiple files
|
||||||
//
|
//
|
||||||
// const hiHandler: RouteHandler<Env> = ({ res }) => {
|
// const helloHandler: Handler = async () => {
|
||||||
// res.body = 'Hello World'
|
// return new Response('Hello World')
|
||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
// router.get('/hi', hiHandler)
|
// 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) {
|
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||||
return router.handle(request, env, ctx)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -340,9 +383,25 @@ import { Router } from '@tsndr/cloudflare-worker-router'
|
|||||||
|
|
||||||
const router = new Router()
|
const router = new Router()
|
||||||
|
|
||||||
// router.get(/'hi', ({ res }) => {
|
// Enable Debug Mode
|
||||||
// res.body = 'Hello World'
|
//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
|
||||||
|
|
||||||
|
|||||||
38
package-lock.json
generated
38
package-lock.json
generated
@@ -1,50 +1,36 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "3.0.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": "3.0.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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "3.0.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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
145
src/index.ts
145
src/index.ts
@@ -6,10 +6,10 @@
|
|||||||
* @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<TEnv> {
|
export type Route<TEnv, TCtx, TReq> = {
|
||||||
method: string
|
method: string
|
||||||
url: string
|
url: string
|
||||||
handlers: RouterHandler<TEnv>[]
|
handlers: RouterHandler<TEnv, TCtx, TReq>[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,9 +20,10 @@ export interface Route<TEnv> {
|
|||||||
* @property {RouterRequest} req Request Object
|
* @property {RouterRequest} req Request Object
|
||||||
* @property {ExecutionContext} ctx Context Object
|
* @property {ExecutionContext} ctx Context Object
|
||||||
*/
|
*/
|
||||||
export interface RouterContext<TEnv = any> {
|
export type RouterContext<TEnv = any, TCtx = {}, TReq = {}> = TCtx & {
|
||||||
env: TEnv
|
env: TEnv
|
||||||
req: RouterRequest
|
req: RouterRequest<TReq>
|
||||||
|
dbg: boolean
|
||||||
ctx?: ExecutionContext
|
ctx?: ExecutionContext
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,18 +36,23 @@ export interface RouterContext<TEnv = any> {
|
|||||||
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
||||||
* @property {RouterRequestQuery} query Object containing all query parameters
|
* @property {RouterRequestQuery} query Object containing all query parameters
|
||||||
* @property {Headers} headers Request headers object
|
* @property {Headers} headers Request headers object
|
||||||
* @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
|
* @property {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<TReq> = TReq & {
|
||||||
url: string
|
url: string
|
||||||
method: string
|
method: string
|
||||||
params: RouterRequestParams
|
params: RouterRequestParams
|
||||||
query: RouterRequestQuery
|
query: RouterRequestQuery
|
||||||
headers: Headers
|
headers: Headers
|
||||||
body: string | any
|
raw: Request
|
||||||
|
arrayBuffer(): Promise<ArrayBuffer>
|
||||||
|
text(): Promise<string>
|
||||||
|
json<T>(): Promise<T>
|
||||||
|
formData(): Promise<FormData>
|
||||||
|
blob(): Promise<Blob>
|
||||||
|
bearer: () => string | undefined
|
||||||
cf?: IncomingRequestCfProperties
|
cf?: IncomingRequestCfProperties
|
||||||
[key: string]: any
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,7 +60,7 @@ export interface RouterRequest {
|
|||||||
*
|
*
|
||||||
* @typedef RouterRequestParams
|
* @typedef RouterRequestParams
|
||||||
*/
|
*/
|
||||||
export interface RouterRequestParams {
|
export type RouterRequestParams = {
|
||||||
[key: string]: string
|
[key: string]: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,7 +69,7 @@ export interface RouterRequestParams {
|
|||||||
*
|
*
|
||||||
* @typedef RouterRequestQuery
|
* @typedef RouterRequestQuery
|
||||||
*/
|
*/
|
||||||
export interface RouterRequestQuery {
|
export type RouterRequestQuery = {
|
||||||
[key: string]: string
|
[key: string]: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,8 +80,8 @@ export interface RouterRequestQuery {
|
|||||||
* @param {RouterContext} ctx
|
* @param {RouterContext} ctx
|
||||||
* @returns {Promise<Response | void> Response | void}
|
* @returns {Promise<Response | void> Response | void}
|
||||||
*/
|
*/
|
||||||
export interface RouterHandler<TEnv = any> {
|
export type RouterHandler<TEnv = any, TCtx = {}, TReq = {}> = {
|
||||||
(ctx: RouterContext<TEnv>): Promise<Response | void> | Response | void
|
(ctx: RouterContext<TEnv, TCtx, TReq>): Promise<Response | void> | Response | void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,24 +91,36 @@ export interface RouterHandler<TEnv = any> {
|
|||||||
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
|
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
|
||||||
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
|
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
|
||||||
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
|
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
|
||||||
|
* @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} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
||||||
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||||
*/
|
*/
|
||||||
export interface RouterCorsConfig {
|
export type RouterCorsConfig = {
|
||||||
allowOrigin?: string
|
allowOrigin?: string
|
||||||
allowMethods?: string
|
allowMethods?: string
|
||||||
allowHeaders?: string
|
allowHeaders?: string
|
||||||
|
allowCredentials?: boolean
|
||||||
|
vary?: string
|
||||||
maxAge?: number
|
maxAge?: number
|
||||||
optionsSuccessStatus?: number
|
optionsSuccessStatus?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type RouterBuffer = {
|
||||||
|
arrayBuffer?: ArrayBuffer
|
||||||
|
text?: string
|
||||||
|
json?: any
|
||||||
|
formData?: FormData
|
||||||
|
blob?: Blob
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router
|
* Router
|
||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
* @class
|
* @class
|
||||||
*/
|
*/
|
||||||
export class Router<TEnv = any> {
|
export class Router<TEnv = any, TCtx = {}, TReq = {}> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Array
|
* Router Array
|
||||||
@@ -110,7 +128,7 @@ export class Router<TEnv = any> {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {Route[]}
|
* @type {Route[]}
|
||||||
*/
|
*/
|
||||||
protected routes: Route<TEnv>[] = []
|
protected routes: Route<TEnv, TCtx, TReq>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global Handlers
|
* Global Handlers
|
||||||
@@ -118,7 +136,7 @@ export class Router<TEnv = any> {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {RouterHandler[]}
|
* @type {RouterHandler[]}
|
||||||
*/
|
*/
|
||||||
protected globalHandlers: RouterHandler<TEnv>[] = []
|
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Debug Mode
|
* Debug Mode
|
||||||
@@ -150,7 +168,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public use(...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public use(...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
for (let handler of handlers) {
|
for (let handler of handlers) {
|
||||||
this.globalHandlers.push(handler)
|
this.globalHandlers.push(handler)
|
||||||
}
|
}
|
||||||
@@ -164,7 +182,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public connect(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public connect(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('CONNECT', url, handlers)
|
return this.register('CONNECT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +193,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public delete(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public delete(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('DELETE', url, handlers)
|
return this.register('DELETE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +204,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public get(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public get(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('GET', url, handlers)
|
return this.register('GET', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,7 +215,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public head(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public head(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('HEAD', url, handlers)
|
return this.register('HEAD', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +226,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public options(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public options(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('OPTIONS', url, handlers)
|
return this.register('OPTIONS', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,7 +237,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public patch(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public patch(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('PATCH', url, handlers)
|
return this.register('PATCH', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +248,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public post(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public post(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('POST', url, handlers)
|
return this.register('POST', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +259,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public put(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public put(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('PUT', url, handlers)
|
return this.register('PUT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,7 +270,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public trace(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public trace(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('TRACE', url, handlers)
|
return this.register('TRACE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +281,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public any(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
public any(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
return this.register('*', url, handlers)
|
return this.register('*', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,7 +291,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public debug(state: boolean = true): Router<TEnv> {
|
public debug(state: boolean = true): Router<TEnv, TCtx, TReq> {
|
||||||
this.debugMode = state
|
this.debugMode = state
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
@@ -284,14 +302,16 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterCorsConfig} [config]
|
* @param {RouterCorsConfig} [config]
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public cors(config?: RouterCorsConfig): Router<TEnv> {
|
public cors(config?: RouterCorsConfig): Router<TEnv, TCtx, TReq> {
|
||||||
this.corsEnabled = true
|
this.corsEnabled = true
|
||||||
this.corsConfig = {
|
this.corsConfig = {
|
||||||
allowOrigin: config?.allowOrigin || '*',
|
allowOrigin: config?.allowOrigin ?? '*',
|
||||||
allowMethods: config?.allowMethods || '*',
|
allowMethods: config?.allowMethods ?? '*',
|
||||||
allowHeaders: config?.allowHeaders || '*',
|
allowHeaders: config?.allowHeaders ?? '*',
|
||||||
maxAge: config?.maxAge || 86400,
|
allowCredentials: config?.allowCredentials ?? undefined,
|
||||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
vary: config?.vary ?? undefined,
|
||||||
|
maxAge: config?.maxAge ?? 86400,
|
||||||
|
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
||||||
}
|
}
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
@@ -303,6 +323,10 @@ export class Router<TEnv = any> {
|
|||||||
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||||
if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
|
if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
|
||||||
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||||
|
if (this.corsConfig.allowCredentials && !headers.has('Access-Control-Allow-Credentials'))
|
||||||
|
headers.set('Access-Control-Allow-Credentials', this.corsConfig.allowCredentials.toString())
|
||||||
|
if (this.corsConfig.vary && !headers.has('vary'))
|
||||||
|
headers.set('vary', this.corsConfig.vary.toString())
|
||||||
if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
|
if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
|
||||||
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||||
return headers
|
return headers
|
||||||
@@ -317,7 +341,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> {
|
private register(method: string, url: string, handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
||||||
this.routes.push({
|
this.routes.push({
|
||||||
method,
|
method,
|
||||||
url,
|
url,
|
||||||
@@ -334,7 +358,7 @@ export class Router<TEnv = any> {
|
|||||||
* @param {RouterRequest} request
|
* @param {RouterRequest} request
|
||||||
* @returns {Route | undefined}
|
* @returns {Route | undefined}
|
||||||
*/
|
*/
|
||||||
private getRoute(request: RouterRequest): Route<TEnv> | undefined {
|
private getRoute(request: RouterRequest<TReq>): Route<TEnv, TCtx, TReq> | undefined {
|
||||||
const url = new URL(request.url)
|
const url = new URL(request.url)
|
||||||
const pathArr = url.pathname.split('/').filter(i => i)
|
const pathArr = url.pathname.split('/').filter(i => i)
|
||||||
|
|
||||||
@@ -368,30 +392,33 @@ export class Router<TEnv = any> {
|
|||||||
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle requests
|
* Handle requests
|
||||||
*
|
*
|
||||||
* @param {TEnv} env
|
|
||||||
* @param {Request} request
|
* @param {Request} request
|
||||||
* @param {any} [extend]
|
* @param {TEnv} env
|
||||||
|
* @param {TCtx} [extCtx]
|
||||||
|
* @param {TReq} [extReq]
|
||||||
* @returns {Promise<Response>}
|
* @returns {Promise<Response>}
|
||||||
*/
|
*/
|
||||||
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extend: any = {}): Promise<Response> {
|
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extCtx?: TCtx, extReq?: TReq): Promise<Response> {
|
||||||
const req: RouterRequest = {
|
const buffer: RouterBuffer = {};
|
||||||
...extend,
|
const req = {
|
||||||
|
...(extReq ?? {}),
|
||||||
method: request.method,
|
method: request.method,
|
||||||
headers: request.headers,
|
headers: request.headers,
|
||||||
url: request.url,
|
url: request.url,
|
||||||
cf: request.cf,
|
cf: request.cf,
|
||||||
|
raw: request,
|
||||||
params: {},
|
params: {},
|
||||||
query: {},
|
query: {},
|
||||||
body: ''
|
arrayBuffer: async (): Promise<ArrayBuffer> => buffer.arrayBuffer ? buffer.arrayBuffer : buffer.arrayBuffer = await request.clone().arrayBuffer(),
|
||||||
}
|
text: async (): Promise<string> => buffer.text ? buffer.text : buffer.text = await request.clone().text(),
|
||||||
|
json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
|
||||||
const route = this.getRoute(req)
|
formData: async (): Promise<FormData> => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(),
|
||||||
|
blob: async (): Promise<Blob> => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(),
|
||||||
if (!route)
|
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
|
||||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
} as RouterRequest<TReq>
|
||||||
|
|
||||||
if (this.corsEnabled && req.method === 'OPTIONS') {
|
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
@@ -400,12 +427,26 @@ export class Router<TEnv = any> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 handlers = [...this.globalHandlers, ...route.handlers]
|
||||||
|
const dbg = this.debugMode
|
||||||
|
|
||||||
let response: Response | undefined
|
let response: Response | undefined
|
||||||
|
|
||||||
for (const handler of handlers) {
|
for (const handler of handlers) {
|
||||||
const res = await handler({ env, req, ctx })
|
const context = {
|
||||||
|
...(extCtx ?? {}),
|
||||||
|
env,
|
||||||
|
req,
|
||||||
|
dbg,
|
||||||
|
ctx
|
||||||
|
} as RouterContext<TEnv, TCtx, TReq>
|
||||||
|
|
||||||
|
const res = await handler(context)
|
||||||
|
|
||||||
if (res) {
|
if (res) {
|
||||||
response = res
|
response = res
|
||||||
@@ -416,8 +457,10 @@ export class Router<TEnv = any> {
|
|||||||
if (!response)
|
if (!response)
|
||||||
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
||||||
|
|
||||||
if (this.corsEnabled)
|
if (this.corsEnabled) {
|
||||||
|
response = new Response(response.body, response)
|
||||||
this.setCorsHeaders(response.headers)
|
this.setCorsHeaders(response.headers)
|
||||||
|
}
|
||||||
|
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user