1
0

53 Commits

Author SHA1 Message Date
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
8 changed files with 274 additions and 185 deletions

View File

@@ -7,3 +7,7 @@ insert_final_newline = false
[src/**.ts]
charset = utf-8
indent_style = tab
[README.md]
indent_style = space
indent_size = 4

View File

@@ -1,4 +1,4 @@
name: Publish (pre)
name: Publish (main)
on:
release:
@@ -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
@@ -20,11 +20,12 @@ jobs:
- name: Publish to npmjs
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
run: npm publish --tag pre --access public
- uses: actions/setup-node@v1
run: npm publish --tag latest --access public
- uses: actions/setup-node@v3
with:
node-version: latest
registry-url: https://npm.pkg.github.com/
- name: Publish to GPR
env:
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
run: npm publish --tag pre --access public
run: npm publish --tag latest --access public

1
.nvmrc
View File

@@ -1 +0,0 @@
v16

View File

@@ -1,71 +1,69 @@
# 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)
- [Fetch](#fetch--routerhandle)
- [Update Router](#update-router)
- [Handlers](#handlers)
## 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>

133
README.md
View File

@@ -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,18 @@ 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 {
// 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
//
@@ -41,22 +47,32 @@ export interface Env {
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
// MY_BUCKET: R2Bucket
SECRET_TOKEN: string
ENVIRONMENT: Var<'dev' | 'prod'>
SECRET_TOKEN: Secret
}
// Initialize router
const router = new Router<Env>()
// 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()
// 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 +101,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 +135,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 +151,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 +167,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...
@@ -215,10 +227,12 @@ If enabled will overwrite other `OPTIONS` requests.
#### `config` (object, optional)
Key | Type | Default Value
---------------------- | --------- | -------------
-------------------------- | ---------- | -------------
`allowOrigin` | `string` | `*`
`allowMethods` | `string` | `*`
`allowHeaders` | `string` | `*`
`allowCredentials` | `boolean` | `undefined`
`vary` | `string` | `undefined`
`maxAge` | `integer` | `86400`
`optionsSuccessStatus` | `integer` | `204`
@@ -268,7 +282,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 +305,11 @@ npm i -D @tsndr/cloudflare-worker-router
```typescript
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/
// MY_KV_NAMESPACE: KVNamespace
//
@@ -300,25 +318,50 @@ export interface Env {
//
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
// 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
//
// 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 helloHandler: Handler = async () => {
// return new Response('Hello World')
// }
//
// router.get('/hi', hiHandler)
// router.get('/hellow', helloHandler)
// TODO: add your routes here
@@ -340,9 +383,25 @@ import { Router } from '@tsndr/cloudflare-worker-router'
const router = new Router()
// router.get(/'hi', ({ res }) => {
// res.body = 'Hello World'
// 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

40
package-lock.json generated
View File

@@ -1,50 +1,36 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-3",
"lockfileVersion": 2,
"version": "3.1.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-3",
"version": "3.1.2",
"license": "MIT",
"devDependencies": {
"@cloudflare/workers-types": "^3.13.0",
"typescript": "^4.7.4"
"@cloudflare/workers-types": "^4.20231025.0",
"typescript": "^5.2.2"
}
},
"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.20231025.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20231025.0.tgz",
"integrity": "sha512-TkcZkntUTOcvJ4vgmwpNfLTclpMbmbClZCe62B25/VTukmyv91joRa4eKzSjzCZUXTbFHNmVdOpmGaaJU2U3+A==",
"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.2.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz",
"integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==",
"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": ">=14.17"
}
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-3",
"version": "3.1.2",
"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.20231025.0",
"typescript": "^5.2.2"
}
}

View File

@@ -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
}
/**
@@ -85,24 +91,36 @@ export interface RouterHandler<TEnv = any> {
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
* @property {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 interface RouterCorsConfig {
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
}
/**
* Router
*
* @public
* @class
*/
export class Router<TEnv = any> {
export class Router<TEnv = any, TCtx = any, TReq = any> {
/**
* Router Array
@@ -110,7 +128,7 @@ export class Router<TEnv = any> {
* @protected
* @type {Route[]}
*/
protected routes: Route<TEnv>[] = []
protected routes: Route<TEnv, TCtx, TReq>[] = []
/**
* Global Handlers
@@ -118,7 +136,7 @@ export class Router<TEnv = any> {
* @protected
* @type {RouterHandler[]}
*/
protected globalHandlers: RouterHandler<TEnv>[] = []
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
/**
* Debug Mode
@@ -150,7 +168,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 +182,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 +193,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 +204,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 +215,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 +226,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 +237,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 +248,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 +259,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 +270,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 +281,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 +291,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 +302,16 @@ 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 ?? '*',
allowCredentials: config?.allowCredentials ?? undefined,
vary: config?.vary ?? undefined,
maxAge: config?.maxAge ?? 86400,
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
}
return this
}
@@ -303,6 +323,10 @@ export class Router<TEnv = any> {
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
if (this.corsConfig.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'))
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
return headers
@@ -317,7 +341,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 +358,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 +395,16 @@ 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 buffer: RouterBuffer = {};
const req = {
...(extReq ?? {}),
method: request.method,
headers: request.headers,
url: request.url,
@@ -386,13 +412,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> => 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>(),
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(),
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 +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 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 +457,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
}