Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
3aaecd8877
|
|||
|
d8d13c4339
|
|||
|
09d5586cc6
|
|||
|
110bfdd95c
|
|||
|
c68a979614
|
|||
|
a4fd646d6b
|
|||
|
606d5f1cb2
|
|||
|
95ccb2263a
|
|||
|
dc88d900cb
|
|||
|
0dca90f4f9
|
|||
|
cb8724edc4
|
|||
|
08c329ff20
|
|||
|
e9a0a2436d
|
|||
|
76d7040a1b
|
|||
|
0037fb64ea
|
|||
|
|
a5ccf0fc01 | ||
|
|
e006d0a3b1 | ||
|
|
c7d7a642e6 | ||
|
|
49c7897bd0 | ||
|
e28976a4b6
|
|||
|
eea9e580f6
|
|||
|
68e614b3fa
|
|||
|
7a20454f79
|
|||
|
101de4f5f6
|
|||
|
9ee1182fa9
|
|||
|
0309b0131f
|
|||
|
afd7ea662f
|
|||
|
a742753cb7
|
|||
|
d631645b99
|
|||
|
cb1bf98053
|
@@ -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
|
||||||
@@ -7,7 +7,6 @@ From `v2.x.x` to `v3.x.x`.
|
|||||||
|
|
||||||
- [Update Router](#update-router)
|
- [Update Router](#update-router)
|
||||||
- [Handlers](#handlers)
|
- [Handlers](#handlers)
|
||||||
- [Fetch](#fetch--routerhandle)
|
|
||||||
|
|
||||||
|
|
||||||
## Update Router
|
## Update Router
|
||||||
@@ -15,7 +14,7 @@ From `v2.x.x` to `v3.x.x`.
|
|||||||
Update to the latest version version of the router.
|
Update to the latest version version of the router.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i -D @tsndr/cloudflare-worker-router
|
npm i -D @tsndr/cloudflare-worker-router@^3
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
91
README.md
91
README.md
@@ -33,6 +33,10 @@ Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
|
|||||||
```typescript
|
```typescript
|
||||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
|
// Env Types
|
||||||
|
export type Var<T = string> = T
|
||||||
|
export type Secret<T = string> = T
|
||||||
|
|
||||||
export type Env = {
|
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
|
||||||
@@ -43,11 +47,23 @@ export type 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()
|
||||||
@@ -210,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
|
||||||
@@ -287,6 +305,10 @@ npm i -D @tsndr/cloudflare-worker-router
|
|||||||
```typescript
|
```typescript
|
||||||
import { Router } from '@tsndr/cloudflare-worker-router'
|
import { Router } from '@tsndr/cloudflare-worker-router'
|
||||||
|
|
||||||
|
// Env Types
|
||||||
|
export type Var<T = string> = T
|
||||||
|
export type Secret<T = string> = T
|
||||||
|
|
||||||
export type Env = {
|
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
|
||||||
@@ -296,32 +318,57 @@ export type 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', async () => {
|
// router.get('/hi', async () => {
|
||||||
// return new Response('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> = async () => {
|
// const helloHandler: Handler = async () => {
|
||||||
// return new Response('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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -336,6 +383,12 @@ import { Router } from '@tsndr/cloudflare-worker-router'
|
|||||||
|
|
||||||
const router = new Router()
|
const router = new Router()
|
||||||
|
|
||||||
|
// Enable Debug Mode
|
||||||
|
//router.debug()
|
||||||
|
|
||||||
|
// Enabling build in CORS support
|
||||||
|
//router.cors()
|
||||||
|
|
||||||
/// Example Route
|
/// Example Route
|
||||||
//
|
//
|
||||||
// router.get('/hi', async () => {
|
// router.get('/hi', async () => {
|
||||||
|
|||||||
9
jest.config.ts
Normal file
9
jest.config.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { Config } from 'jest'
|
||||||
|
|
||||||
|
const config: Config = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
verbose: true
|
||||||
|
}
|
||||||
|
|
||||||
|
export default config
|
||||||
3899
package-lock.json
generated
3899
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@@ -1,11 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "3.0.0-13",
|
"version": "3.2.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc"
|
"build": "tsc",
|
||||||
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -31,7 +32,12 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^4.20230307.0",
|
"@cloudflare/workers-types": "^4.20231025.0",
|
||||||
"typescript": "^4.9.5"
|
"@jest/globals": "^29.7.0",
|
||||||
|
"@types/jest": "^29.5.11",
|
||||||
|
"jest": "^29.7.0",
|
||||||
|
"ts-jest": "^29.1.1",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"typescript": "^5.2.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
366
src/index.spec.ts
Normal file
366
src/index.spec.ts
Normal file
@@ -0,0 +1,366 @@
|
|||||||
|
import { describe, expect, test } from '@jest/globals'
|
||||||
|
import { Router } from '.'
|
||||||
|
|
||||||
|
describe('Router', () => {
|
||||||
|
test('use', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.use(() => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
router.get('/', () => new Response('failed'))
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('delete', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'DELETE' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.delete('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('get', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'GET' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.get('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('head', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'HEAD' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.head('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('options', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'OPTIONS' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.options('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('patch', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'PATCH' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.patch('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('post', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.post('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.post('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('put', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'PUT' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.put('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.put('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('any', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.any('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.any('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cors', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'GET' })
|
||||||
|
const testOptionsRequest = new Request('https://example.com/', { method: 'OPTIONS' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.cors()).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
router.get('/', () => testResponse)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Methods')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Headers')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Credentials')).toBe(null)
|
||||||
|
expect(response.headers.get('vary')).toBe(null)
|
||||||
|
expect(response.headers.get('Access-Control-Max-Age')).toBe('86400')
|
||||||
|
|
||||||
|
const optionsRes = await router.handle(testOptionsRequest, {})
|
||||||
|
|
||||||
|
expect(optionsRes.status).toBe(204)
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Origin')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Methods')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Headers')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Credentials')).toBe(null)
|
||||||
|
expect(optionsRes.headers.get('vary')).toBe(null)
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Max-Age')).toBe('86400')
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('params', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/bar/foo')
|
||||||
|
|
||||||
|
router.get('/:foo/:bar', ({ req }) => {
|
||||||
|
return Response.json(req.params)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ foo: 'bar', bar: 'foo' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('query', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/?foo=bar&bar=foo')
|
||||||
|
|
||||||
|
router.get('/', ({ req }) => {
|
||||||
|
return Response.json(req.query)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ foo: 'bar', bar: 'foo' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('404', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('debug mode', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
router.debug()
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('Route not found!')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('handler no response', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
router.debug()
|
||||||
|
|
||||||
|
router.get('/', () => {})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('Handler did not return a Response!')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('wildcard', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/foo/bar')
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
router.get('*', () => testResponse)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('bearer', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testToken = 'super-secret-token'
|
||||||
|
const testRequest = new Request('https://example.com/', { headers: { 'Authorization': `Bearer ${testToken}` }})
|
||||||
|
|
||||||
|
router.get('/', ({ req }) => new Response(req.bearer()))
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe(testToken)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Middleware', () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testHandlerSuccess = () => new Response('success', { status: 200 })
|
||||||
|
const testHandlerContinue = () => {}
|
||||||
|
const testHandlerFailed = () => new Response('failed', { status: 403 })
|
||||||
|
|
||||||
|
router.get('/success', testHandlerContinue, testHandlerSuccess)
|
||||||
|
router.get('/failed', testHandlerFailed, testHandlerSuccess)
|
||||||
|
|
||||||
|
test('continue', async () => {
|
||||||
|
const testRequest = new Request('https://example.com/success')
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('block', async () => {
|
||||||
|
const testRequest = new Request('https://example.com/failed')
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(403)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('failed')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Body', () => {
|
||||||
|
|
||||||
|
test('text then text', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testText = "lorem ipsum dolor sit amet"
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testText })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
text: await req.text(),
|
||||||
|
text2: await req.text()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testText, text2: testText })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('json then json', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
json: await req.json(),
|
||||||
|
json2: await req.json()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ json: testObject, json2: testObject })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('text then json', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
text: await req.text(),
|
||||||
|
json: await req.json()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testJson, json: testObject })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('json then text', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
json: await req.json(),
|
||||||
|
text: await req.text()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testJson, json: testObject })
|
||||||
|
})
|
||||||
|
})
|
||||||
121
src/index.ts
121
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 type Route<TEnv, TCtx, TReq> = {
|
export type Route<Env, CtxExt, ReqExt> = {
|
||||||
method: string
|
method: string
|
||||||
url: string
|
url: string
|
||||||
handlers: RouterHandler<TEnv, TCtx, TReq>[]
|
handlers: RouterHandler<Env, CtxExt, ReqExt>[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,9 +20,9 @@ export type Route<TEnv, TCtx, TReq> = {
|
|||||||
* @property {RouterRequest} req Request Object
|
* @property {RouterRequest} req Request Object
|
||||||
* @property {ExecutionContext} ctx Context Object
|
* @property {ExecutionContext} ctx Context Object
|
||||||
*/
|
*/
|
||||||
export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
|
export type RouterContext<Env = any, CtxExt = {}, ReqExt = {}> = CtxExt & {
|
||||||
env: TEnv
|
env: Env
|
||||||
req: RouterRequest<TReq>
|
req: RouterRequest<ReqExt>
|
||||||
dbg: boolean
|
dbg: boolean
|
||||||
ctx?: ExecutionContext
|
ctx?: ExecutionContext
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
|
|||||||
* @property {Request} raw Raw Request Object
|
* @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 type RouterRequest<TReq> = TReq & {
|
export type RouterRequest<ReqExt> = ReqExt & {
|
||||||
url: string
|
url: string
|
||||||
method: string
|
method: string
|
||||||
params: RouterRequestParams
|
params: RouterRequestParams
|
||||||
@@ -51,7 +51,7 @@ export type RouterRequest<TReq> = TReq & {
|
|||||||
json<T>(): Promise<T>
|
json<T>(): Promise<T>
|
||||||
formData(): Promise<FormData>
|
formData(): Promise<FormData>
|
||||||
blob(): Promise<Blob>
|
blob(): Promise<Blob>
|
||||||
bearer: () => string | undefined
|
bearer(): string | undefined
|
||||||
cf?: IncomingRequestCfProperties
|
cf?: IncomingRequestCfProperties
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,8 +80,8 @@ export type RouterRequestQuery = {
|
|||||||
* @param {RouterContext} ctx
|
* @param {RouterContext} ctx
|
||||||
* @returns {Promise<Response | void> Response | void}
|
* @returns {Promise<Response | void> Response | void}
|
||||||
*/
|
*/
|
||||||
export type RouterHandler<TEnv = any, TCtx = any, TReq = any> = {
|
export type RouterHandler<Env = any, CtxExt = {}, ReqExt = {}> = {
|
||||||
(ctx: RouterContext<TEnv, TCtx, TReq>): Promise<Response | void> | Response | void
|
(ctx: RouterContext<Env, CtxExt, ReqExt>): Promise<Response | void> | Response | void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -91,6 +91,8 @@ export type RouterHandler<TEnv = any, TCtx = any, TReq = 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`)
|
||||||
*/
|
*/
|
||||||
@@ -98,6 +100,8 @@ 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
|
||||||
}
|
}
|
||||||
@@ -116,7 +120,7 @@ export type RouterBuffer = {
|
|||||||
* @public
|
* @public
|
||||||
* @class
|
* @class
|
||||||
*/
|
*/
|
||||||
export class Router<TEnv = any, TCtx = any, TReq = any> {
|
export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Array
|
* Router Array
|
||||||
@@ -124,7 +128,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {Route[]}
|
* @type {Route[]}
|
||||||
*/
|
*/
|
||||||
protected routes: Route<TEnv, TCtx, TReq>[] = []
|
protected routes: Route<Env, CtxExt, ReqExt>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global Handlers
|
* Global Handlers
|
||||||
@@ -132,7 +136,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @protected
|
* @protected
|
||||||
* @type {RouterHandler[]}
|
* @type {RouterHandler[]}
|
||||||
*/
|
*/
|
||||||
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
|
protected globalHandlers: RouterHandler<Env, CtxExt, ReqExt>[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Debug Mode
|
* Debug Mode
|
||||||
@@ -150,14 +154,6 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
*/
|
*/
|
||||||
protected corsConfig: RouterCorsConfig = {}
|
protected corsConfig: RouterCorsConfig = {}
|
||||||
|
|
||||||
/**
|
|
||||||
* Buffer
|
|
||||||
*
|
|
||||||
* @protected
|
|
||||||
* @type {RouterBuffer}
|
|
||||||
*/
|
|
||||||
protected buffer: RouterBuffer = {}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CORS enabled
|
* CORS enabled
|
||||||
*
|
*
|
||||||
@@ -172,24 +168,13 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public use(...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public use(...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
for (let handler of handlers) {
|
for (let handler of handlers) {
|
||||||
this.globalHandlers.push(handler)
|
this.globalHandlers.push(handler)
|
||||||
}
|
}
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Register CONNECT route
|
|
||||||
*
|
|
||||||
* @param {string} url
|
|
||||||
* @param {RouterHandler[]} handlers
|
|
||||||
* @returns {Router}
|
|
||||||
*/
|
|
||||||
public connect(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
|
||||||
return this.register('CONNECT', url, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register DELETE route
|
* Register DELETE route
|
||||||
*
|
*
|
||||||
@@ -197,7 +182,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public delete(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public delete(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('DELETE', url, handlers)
|
return this.register('DELETE', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +193,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public get(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public get(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('GET', url, handlers)
|
return this.register('GET', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,7 +204,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public head(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public head(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('HEAD', url, handlers)
|
return this.register('HEAD', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +215,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public options(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public options(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('OPTIONS', url, handlers)
|
return this.register('OPTIONS', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +226,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public patch(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public patch(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('PATCH', url, handlers)
|
return this.register('PATCH', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,7 +237,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public post(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public post(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('POST', url, handlers)
|
return this.register('POST', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,21 +248,10 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public put(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public put(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('PUT', url, handlers)
|
return this.register('PUT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Register TRACE route
|
|
||||||
*
|
|
||||||
* @param {string} url
|
|
||||||
* @param {RouterHandler[]} handlers
|
|
||||||
* @returns {Router}
|
|
||||||
*/
|
|
||||||
public trace(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
|
||||||
return this.register('TRACE', url, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register route, ignoring method
|
* Register route, ignoring method
|
||||||
*
|
*
|
||||||
@@ -285,7 +259,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterHandler[]} handlers
|
* @param {RouterHandler[]} handlers
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public any(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
public any(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
return this.register('*', url, handlers)
|
return this.register('*', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,7 +269,7 @@ export class Router<TEnv = any, TCtx = any, TReq = 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, TCtx, TReq> {
|
public debug(state: boolean = true): Router<Env, CtxExt, ReqExt> {
|
||||||
this.debugMode = state
|
this.debugMode = state
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
@@ -306,12 +280,14 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterCorsConfig} [config]
|
* @param {RouterCorsConfig} [config]
|
||||||
* @returns {Router}
|
* @returns {Router}
|
||||||
*/
|
*/
|
||||||
public cors(config?: RouterCorsConfig): Router<TEnv, TCtx, TReq> {
|
public cors(config?: RouterCorsConfig): Router<Env, CtxExt, ReqExt> {
|
||||||
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 ?? '*',
|
||||||
|
allowCredentials: config?.allowCredentials ?? undefined,
|
||||||
|
vary: config?.vary ?? undefined,
|
||||||
maxAge: config?.maxAge ?? 86400,
|
maxAge: config?.maxAge ?? 86400,
|
||||||
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
||||||
}
|
}
|
||||||
@@ -325,6 +301,10 @@ export class Router<TEnv = any, TCtx = any, TReq = 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
|
||||||
@@ -339,7 +319,7 @@ export class Router<TEnv = any, TCtx = any, TReq = 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, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
|
private register(method: string, url: string, handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
this.routes.push({
|
this.routes.push({
|
||||||
method,
|
method,
|
||||||
url,
|
url,
|
||||||
@@ -356,7 +336,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
* @param {RouterRequest} request
|
* @param {RouterRequest} request
|
||||||
* @returns {Route | undefined}
|
* @returns {Route | undefined}
|
||||||
*/
|
*/
|
||||||
private getRoute(request: RouterRequest<TReq>): Route<TEnv, TCtx, TReq> | undefined {
|
private getRoute(request: RouterRequest<ReqExt>): Route<Env, CtxExt, ReqExt> | 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)
|
||||||
|
|
||||||
@@ -390,18 +370,19 @@ export class Router<TEnv = any, TCtx = any, TReq = 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 {Request} request
|
* @param {Request} request
|
||||||
* @param {TEnv} env
|
* @param {Env} env
|
||||||
* @param {TCtx} [extCtx]
|
* @param {CtxExt} [ctxExt]
|
||||||
* @param {TReq} [extReq]
|
* @param {ReqExt} [reqExt]
|
||||||
* @returns {Promise<Response>}
|
* @returns {Promise<Response>}
|
||||||
*/
|
*/
|
||||||
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extCtx?: TCtx, extReq?: TReq): Promise<Response> {
|
public async handle(request: Request, env: Env, ctx?: ExecutionContext, ctxExt?: CtxExt, reqExt?: ReqExt): Promise<Response> {
|
||||||
|
const buffer: RouterBuffer = {}
|
||||||
const req = {
|
const req = {
|
||||||
...(extReq ?? {}),
|
...(reqExt ?? {}),
|
||||||
method: request.method,
|
method: request.method,
|
||||||
headers: request.headers,
|
headers: request.headers,
|
||||||
url: request.url,
|
url: request.url,
|
||||||
@@ -409,13 +390,13 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
raw: request,
|
raw: request,
|
||||||
params: {},
|
params: {},
|
||||||
query: {},
|
query: {},
|
||||||
arrayBuffer: async (): Promise<ArrayBuffer> => this.buffer.arrayBuffer ? this.buffer.arrayBuffer : this.buffer.arrayBuffer = await request.arrayBuffer(),
|
arrayBuffer: async (): Promise<ArrayBuffer> => buffer.arrayBuffer ? buffer.arrayBuffer : buffer.arrayBuffer = await request.clone().arrayBuffer(),
|
||||||
text: async (): Promise<string> => this.buffer.text ? this.buffer.text : this.buffer.text = await request.text(),
|
text: async (): Promise<string> => buffer.text ? buffer.text : buffer.text = await request.clone().text(),
|
||||||
json: async <T>(): Promise<T> => this.buffer.json ? this.buffer.json : this.buffer.json = await request.json<T>(),
|
json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
|
||||||
formData: async (): Promise<FormData> => this.buffer.formData ? this.buffer.formData : this.buffer.formData = await request.formData(),
|
formData: async (): Promise<FormData> => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(),
|
||||||
blob: async (): Promise<Blob> => this.buffer.blob ? this.buffer.blob : this.buffer.blob = await request.blob(),
|
blob: async (): Promise<Blob> => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(),
|
||||||
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
|
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
|
||||||
} as RouterRequest<TReq>
|
} as RouterRequest<ReqExt>
|
||||||
|
|
||||||
if (this.corsEnabled && req.method === 'OPTIONS') {
|
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
@@ -436,12 +417,12 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
|
|
||||||
for (const handler of handlers) {
|
for (const handler of handlers) {
|
||||||
const context = {
|
const context = {
|
||||||
...(extCtx ?? {}),
|
...(ctxExt ?? {}),
|
||||||
env,
|
env,
|
||||||
req,
|
req,
|
||||||
dbg,
|
dbg,
|
||||||
ctx
|
ctx
|
||||||
} as RouterContext<TEnv, TCtx, TReq>
|
} as RouterContext<Env, CtxExt, ReqExt>
|
||||||
|
|
||||||
const res = await handler(context)
|
const res = await handler(context)
|
||||||
|
|
||||||
@@ -461,4 +442,4 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
|
|||||||
|
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user