Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
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
|
5
.github/workflows/publish-pre.yml
vendored
5
.github/workflows/publish-pre.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 'latest'
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
@@ -21,8 +21,9 @@ jobs:
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
run: npm publish --tag pre --access public
|
||||
- uses: actions/setup-node@v1
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 'latest'
|
||||
registry-url: https://npm.pkg.github.com/
|
||||
- name: Publish to GPR
|
||||
env:
|
||||
|
||||
95
MIGRATION.md
95
MIGRATION.md
@@ -1,71 +1,70 @@
|
||||
# Migration Guide
|
||||
|
||||
From `v1.x.x` to `v2.x.x`.
|
||||
From `v2.x.x` to `v3.x.x`.
|
||||
|
||||
|
||||
## Contents
|
||||
|
||||
- [Preparation](#preparation)
|
||||
- [Update](#update)
|
||||
- [Import / Require](#import--require)
|
||||
- [Routes](#routes)
|
||||
- [Update Router](#update-router)
|
||||
- [Handlers](#handlers)
|
||||
- [Fetch](#fetch--routerhandle)
|
||||
|
||||
|
||||
## Preparation
|
||||
## Update Router
|
||||
|
||||
Follow Cloudflare's [Migration Guide](https://developers.cloudflare.com/workers/wrangler/migration/migrating-from-wrangler-1/) to update your protject to [wrangler2](https://github.com/cloudflare/wrangler2).
|
||||
|
||||
## Update
|
||||
|
||||
Update to the latest version verstion
|
||||
Update to the latest version version of the router.
|
||||
|
||||
```bash
|
||||
npm i -D @tsndr/cloudflare-worker-router
|
||||
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
|
||||
|
||||
```javascript
|
||||
const Router = require('@tsndr/cloudflare-worker-router')
|
||||
```typescript
|
||||
// Register global middleware
|
||||
router.use(({ env, req, res, next }) => {
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
|
||||
res.status = 401
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
|
||||
// Simple get
|
||||
router.get('/user', ({ res }) => {
|
||||
res.body = {
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### After
|
||||
|
||||
```javascript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
```typescript
|
||||
// Register global middleware
|
||||
router.use(({ env, req }) => {
|
||||
// Intercept if token doesn't match
|
||||
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
|
||||
return new Response(null, { status: 401 })
|
||||
}
|
||||
})
|
||||
|
||||
// Simple get
|
||||
router.get('/user', () => {
|
||||
return Response.json({
|
||||
id: 1,
|
||||
name: 'John Doe'
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Routes
|
||||
|
||||
Just add curly braces.
|
||||
|
||||
|
||||
### Before
|
||||
|
||||
<a href="https://gist.github.com/tsndr/34e8544266ae15d51abd019d7c3d27ca" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 57 01 PM" src="https://user-images.githubusercontent.com/2940127/175572731-a8729c1b-15e2-45ac-be80-7e8527c5502a.png"></a>
|
||||
|
||||
|
||||
### After
|
||||
|
||||
<a href="https://gist.github.com/tsndr/8db6e8dd55e348015c2ff8e93dd6aa31" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 55 56 PM" src="https://user-images.githubusercontent.com/2940127/175572549-0eea8fc4-3d90-412a-89cc-d2f4569f1139.png"></a>
|
||||
|
||||
|
||||
## Fetch / `router.handle()`
|
||||
|
||||
❗️ Be aware that with `v2.0.0` the parameters of `router.handle()` changed ❗️
|
||||
|
||||
|
||||
### Before
|
||||
|
||||
<a href="https://gist.github.com/tsndr/12b0f800269760c597646c90a562ef88" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 58 43 PM" src="https://user-images.githubusercontent.com/2940127/175572993-fb4681c2-eece-4c92-88e8-1c2f57644769.png"></a>
|
||||
|
||||
|
||||
### After
|
||||
|
||||
<a href="https://gist.github.com/tsndr/30902b01b134e2a58cf3a53648dd3e47" target="_blank"><img width="393" alt="Petrify 2022-06-24 at 5 59 22 PM" src="https://user-images.githubusercontent.com/2940127/175573110-b7dfcfb2-855d-4529-a957-6f8b9ec439f3.png"></a>
|
||||
|
||||
66
README.md
66
README.md
@@ -12,7 +12,7 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
||||
- [Features](#features)
|
||||
- [Usage](#usage)
|
||||
- [Reference](#reference)
|
||||
- [Setup](#setup)
|
||||
- [Getting started](#getting-started)
|
||||
|
||||
|
||||
## Features
|
||||
@@ -26,12 +26,14 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
||||
|
||||
## Usage
|
||||
|
||||
Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
|
||||
|
||||
### TypeScript Example
|
||||
|
||||
```typescript
|
||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
export interface Env {
|
||||
export type Env = {
|
||||
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
|
||||
// MY_KV_NAMESPACE: KVNamespace
|
||||
//
|
||||
@@ -51,12 +53,10 @@ const router = new Router<Env>()
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
router.use(() => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'X-Global-Middlewares': 'true'
|
||||
}
|
||||
})
|
||||
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
|
||||
@@ -85,9 +85,7 @@ router.post('/user/:id', ({ req }) => {
|
||||
|
||||
// Delete route using a middleware
|
||||
router.delete('/user/:id', ({ env, req }) => {
|
||||
const { SECRET_TOKEN } = env
|
||||
|
||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
|
||||
}, ({ req }) => {
|
||||
@@ -121,12 +119,10 @@ const router = new Router()
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
router.use(() => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'X-Global-Middlewares': 'true'
|
||||
}
|
||||
})
|
||||
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
|
||||
@@ -139,11 +135,12 @@ router.get('/user', () => {
|
||||
|
||||
// Post route with url parameter
|
||||
router.post('/user/:id', ({ req }) => {
|
||||
|
||||
const userId = req.params.id
|
||||
|
||||
// Do stuff
|
||||
|
||||
if (errorDoingStuff) {
|
||||
if (!true) {
|
||||
return Response.json({
|
||||
error: 'Error doing stuff!'
|
||||
}, { status: 400 })
|
||||
@@ -154,12 +151,11 @@ router.post('/user/:id', ({ req }) => {
|
||||
|
||||
// Delete route using a middleware
|
||||
router.delete('/user/:id', ({ env, req }) => {
|
||||
const { SECRET_TOKEN } = env
|
||||
|
||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
|
||||
}, ({ req }) => {
|
||||
|
||||
const userId = req.params.id
|
||||
|
||||
// Do stuff...
|
||||
@@ -268,7 +264,7 @@ Key | Type | Description
|
||||
`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.
|
||||
|
||||
@@ -291,7 +287,7 @@ npm i -D @tsndr/cloudflare-worker-router
|
||||
```typescript
|
||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
export interface Env {
|
||||
export type Env = {
|
||||
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
|
||||
// MY_KV_NAMESPACE: KVNamespace
|
||||
//
|
||||
@@ -306,15 +302,15 @@ const router = new Router<Env>()
|
||||
|
||||
/// Example Route
|
||||
//
|
||||
// router.get(/'hi', ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
//}
|
||||
// router.get('/hi', async () => {
|
||||
// return new Response('Hello World')
|
||||
//})
|
||||
|
||||
|
||||
/// Example Route for splitting into multiple files
|
||||
//
|
||||
// const hiHandler: RouteHandler<Env> = ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
// const hiHandler: RouteHandler<Env> = async () => {
|
||||
// return new Response('Hello World')
|
||||
// }
|
||||
//
|
||||
// router.get('/hi', hiHandler)
|
||||
@@ -340,9 +336,19 @@ import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
const router = new Router()
|
||||
|
||||
// router.get(/'hi', ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
/// 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
|
||||
|
||||
|
||||
40
package-lock.json
generated
40
package-lock.json
generated
@@ -1,50 +1,36 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-3",
|
||||
"lockfileVersion": 2,
|
||||
"version": "3.0.0-16",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-3",
|
||||
"version": "3.0.0-16",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
"typescript": "^4.7.4"
|
||||
"@cloudflare/workers-types": "^4.20230518.0",
|
||||
"typescript": "^5.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudflare/workers-types": {
|
||||
"version": "3.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz",
|
||||
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==",
|
||||
"version": "4.20230518.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230518.0.tgz",
|
||||
"integrity": "sha512-A0w1V+5SUawGaaPRlhFhSC/SCDT9oQG8TMoWOKFLA4qbqagELqEAFD4KySBIkeVOvCBLT1DZSYBMCxbXddl0kw==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "4.7.4",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz",
|
||||
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==",
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz",
|
||||
"integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.2.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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
|
||||
"node": ">=12.20"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-3",
|
||||
"version": "3.0.0-16",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
"typescript": "^4.7.4"
|
||||
"@cloudflare/workers-types": "^4.20230518.0",
|
||||
"typescript": "^5.0.4"
|
||||
}
|
||||
}
|
||||
|
||||
139
src/index.ts
139
src/index.ts
@@ -6,10 +6,10 @@
|
||||
* @property {string} url URL String
|
||||
* @property {RouterHandler[]} handlers Array of handler functions
|
||||
*/
|
||||
export interface Route<TEnv> {
|
||||
export type Route<TEnv, TCtx, TReq> = {
|
||||
method: 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 {ExecutionContext} ctx Context Object
|
||||
*/
|
||||
export interface RouterContext<TEnv = any> {
|
||||
export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
|
||||
env: TEnv
|
||||
req: RouterRequest
|
||||
req: RouterRequest<TReq>
|
||||
dbg: boolean
|
||||
ctx?: ExecutionContext
|
||||
}
|
||||
|
||||
@@ -35,18 +36,23 @@ export interface RouterContext<TEnv = any> {
|
||||
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
|
||||
* @property {RouterRequestQuery} query Object containing all query parameters
|
||||
* @property {Headers} headers Request headers object
|
||||
* @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
|
||||
* @property {Request} raw Raw Request 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
|
||||
method: string
|
||||
params: RouterRequestParams
|
||||
query: RouterRequestQuery
|
||||
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
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,7 +60,7 @@ export interface RouterRequest {
|
||||
*
|
||||
* @typedef RouterRequestParams
|
||||
*/
|
||||
export interface RouterRequestParams {
|
||||
export type RouterRequestParams = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -63,7 +69,7 @@ export interface RouterRequestParams {
|
||||
*
|
||||
* @typedef RouterRequestQuery
|
||||
*/
|
||||
export interface RouterRequestQuery {
|
||||
export type RouterRequestQuery = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -74,8 +80,8 @@ export interface RouterRequestQuery {
|
||||
* @param {RouterContext} ctx
|
||||
* @returns {Promise<Response | void> Response | void}
|
||||
*/
|
||||
export interface RouterHandler<TEnv = any> {
|
||||
(ctx: RouterContext<TEnv>): Promise<Response | void> | Response | void
|
||||
export type RouterHandler<TEnv = any, TCtx = any, TReq = any> = {
|
||||
(ctx: RouterContext<TEnv, TCtx, TReq>): Promise<Response | void> | Response | void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,7 +94,7 @@ export interface RouterHandler<TEnv = any> {
|
||||
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
||||
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||
*/
|
||||
export interface RouterCorsConfig {
|
||||
export type RouterCorsConfig = {
|
||||
allowOrigin?: string
|
||||
allowMethods?: string
|
||||
allowHeaders?: string
|
||||
@@ -96,13 +102,21 @@ export interface RouterCorsConfig {
|
||||
optionsSuccessStatus?: number
|
||||
}
|
||||
|
||||
export type RouterBuffer = {
|
||||
arrayBuffer?: ArrayBuffer
|
||||
text?: string
|
||||
json?: any
|
||||
formData?: FormData
|
||||
blob?: Blob
|
||||
}
|
||||
|
||||
/**
|
||||
* Router
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
*/
|
||||
export class Router<TEnv = any> {
|
||||
export class Router<TEnv = any, TCtx = any, TReq = any> {
|
||||
|
||||
/**
|
||||
* Router Array
|
||||
@@ -110,7 +124,7 @@ export class Router<TEnv = any> {
|
||||
* @protected
|
||||
* @type {Route[]}
|
||||
*/
|
||||
protected routes: Route<TEnv>[] = []
|
||||
protected routes: Route<TEnv, TCtx, TReq>[] = []
|
||||
|
||||
/**
|
||||
* Global Handlers
|
||||
@@ -118,7 +132,7 @@ export class Router<TEnv = any> {
|
||||
* @protected
|
||||
* @type {RouterHandler[]}
|
||||
*/
|
||||
protected globalHandlers: RouterHandler<TEnv>[] = []
|
||||
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
|
||||
|
||||
/**
|
||||
* Debug Mode
|
||||
@@ -136,6 +150,14 @@ export class Router<TEnv = any> {
|
||||
*/
|
||||
protected corsConfig: RouterCorsConfig = {}
|
||||
|
||||
/**
|
||||
* Buffer
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterBuffer}
|
||||
*/
|
||||
protected buffer: RouterBuffer = {}
|
||||
|
||||
/**
|
||||
* CORS enabled
|
||||
*
|
||||
@@ -150,7 +172,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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) {
|
||||
this.globalHandlers.push(handler)
|
||||
}
|
||||
@@ -164,7 +186,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -175,7 +197,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -186,7 +208,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -197,7 +219,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -208,7 +230,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -219,7 +241,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -230,7 +252,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -241,7 +263,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -252,7 +274,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -263,7 +285,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers
|
||||
* @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)
|
||||
}
|
||||
|
||||
@@ -273,7 +295,7 @@ export class Router<TEnv = any> {
|
||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||
* @returns {Router}
|
||||
*/
|
||||
public debug(state: boolean = true): Router<TEnv> {
|
||||
public debug(state: boolean = true): Router<TEnv, TCtx, TReq> {
|
||||
this.debugMode = state
|
||||
return this
|
||||
}
|
||||
@@ -284,14 +306,14 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterCorsConfig} [config]
|
||||
* @returns {Router}
|
||||
*/
|
||||
public cors(config?: RouterCorsConfig): Router<TEnv> {
|
||||
public cors(config?: RouterCorsConfig): Router<TEnv, TCtx, TReq> {
|
||||
this.corsEnabled = true
|
||||
this.corsConfig = {
|
||||
allowOrigin: config?.allowOrigin || '*',
|
||||
allowMethods: config?.allowMethods || '*',
|
||||
allowHeaders: config?.allowHeaders || '*',
|
||||
maxAge: config?.maxAge || 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||
allowOrigin: config?.allowOrigin ?? '*',
|
||||
allowMethods: config?.allowMethods ?? '*',
|
||||
allowHeaders: config?.allowHeaders ?? '*',
|
||||
maxAge: config?.maxAge ?? 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
||||
}
|
||||
return this
|
||||
}
|
||||
@@ -317,7 +339,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterHandler[]} handlers Arrar of handler functions
|
||||
* @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({
|
||||
method,
|
||||
url,
|
||||
@@ -334,7 +356,7 @@ export class Router<TEnv = any> {
|
||||
* @param {RouterRequest} request
|
||||
* @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 pathArr = url.pathname.split('/').filter(i => i)
|
||||
|
||||
@@ -371,14 +393,15 @@ export class Router<TEnv = any> {
|
||||
/**
|
||||
* Handle requests
|
||||
*
|
||||
* @param {TEnv} env
|
||||
* @param {Request} request
|
||||
* @param {any} [extend]
|
||||
* @param {TEnv} env
|
||||
* @param {TCtx} [extCtx]
|
||||
* @param {TReq} [extReq]
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extend: any = {}): Promise<Response> {
|
||||
const req: RouterRequest = {
|
||||
...extend,
|
||||
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extCtx?: TCtx, extReq?: TReq): Promise<Response> {
|
||||
const req = {
|
||||
...(extReq ?? {}),
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
url: request.url,
|
||||
@@ -386,13 +409,13 @@ export class Router<TEnv = any> {
|
||||
raw: request,
|
||||
params: {},
|
||||
query: {},
|
||||
body: ''
|
||||
}
|
||||
|
||||
const route = this.getRoute(req)
|
||||
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
arrayBuffer: async (): Promise<ArrayBuffer> => this.buffer.arrayBuffer ? this.buffer.arrayBuffer : this.buffer.arrayBuffer = await request.arrayBuffer(),
|
||||
text: async (): Promise<string> => this.buffer.text ? this.buffer.text : this.buffer.text = await request.text(),
|
||||
json: async <T>(): Promise<T> => this.buffer.json ? this.buffer.json : this.buffer.json = await request.json<T>(),
|
||||
formData: async (): Promise<FormData> => this.buffer.formData ? this.buffer.formData : this.buffer.formData = await request.formData(),
|
||||
blob: async (): Promise<Blob> => this.buffer.blob ? this.buffer.blob : this.buffer.blob = await request.blob(),
|
||||
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
|
||||
} as RouterRequest<TReq>
|
||||
|
||||
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
@@ -401,12 +424,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 dbg = this.debugMode
|
||||
|
||||
let response: Response | undefined
|
||||
|
||||
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) {
|
||||
response = res
|
||||
@@ -417,8 +454,10 @@ export class Router<TEnv = any> {
|
||||
if (!response)
|
||||
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)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user