Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
5fa3475a20
|
|||
|
0637549e90
|
|||
|
f3279e71fc
|
|||
|
bdb7be3699
|
|||
|
45a781ea66
|
|||
|
7f44f304a2
|
|||
|
a786262ec6
|
20
README.md
20
README.md
@@ -24,7 +24,7 @@ import Router from '@tsndr/cloudflare-worker-router'
|
||||
// Initialize router
|
||||
const router = new Router()
|
||||
|
||||
// Enabling buildin CORS support
|
||||
// Enabling build in CORS support
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
@@ -180,21 +180,7 @@ Key | Type | Description
|
||||
|
||||
## Setup
|
||||
|
||||
---
|
||||
### ❗️ Compatibility ❗️
|
||||
|
||||
CLI Tool | Router
|
||||
-------- | ------
|
||||
[wrangler2](https://github.com/cloudflare/wrangler2#readme) | Use `v2.x.x` or later.
|
||||
[@cloudflare/wrangler](https://github.com/cloudflare/wrangler#readme) | Use `v1.x.x`, [here](https://github.com/tsndr/cloudflare-worker-router/tree/legacy#readme).
|
||||
|
||||
See [Migration from v1.x.x to v2.x.x](https://github.com/tsndr/cloudflare-worker-router/blob/main/MIGRATION.md#migration-guide) if you want to update.
|
||||
|
||||
---
|
||||
|
||||
### **[Wrangler2](https://github.com/cloudflare/wrangler2#readme)**
|
||||
|
||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/), then install the router using this command
|
||||
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler, then install the router using this command:
|
||||
|
||||
```bash
|
||||
npm i -D @tsndr/cloudflare-worker-router
|
||||
@@ -247,4 +233,4 @@ export default {
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
</details>
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.2",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.2",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
|
||||
71
src/index.ts
71
src/index.ts
@@ -165,6 +165,14 @@ export default class Router {
|
||||
*/
|
||||
protected corsConfig: RouterCorsConfig = {}
|
||||
|
||||
/**
|
||||
* CORS enabled
|
||||
*-
|
||||
* @protected
|
||||
* @type {boolean}
|
||||
*/
|
||||
protected corsEnabled: boolean = false
|
||||
|
||||
/**
|
||||
* Register global handlers
|
||||
*
|
||||
@@ -306,10 +314,11 @@ export default class Router {
|
||||
* @returns {Router}
|
||||
*/
|
||||
public cors(config?: RouterCorsConfig): Router {
|
||||
this.corsEnabled = true
|
||||
this.corsConfig = {
|
||||
allowOrigin: config?.allowOrigin || '*',
|
||||
allowMethods: config?.allowMethods || '*',
|
||||
allowHeaders: config?.allowHeaders || '*, Authorization',
|
||||
allowHeaders: config?.allowHeaders || '*',
|
||||
maxAge: config?.maxAge || 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||
}
|
||||
@@ -331,6 +340,7 @@ export default class Router {
|
||||
url,
|
||||
handlers
|
||||
})
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
@@ -344,23 +354,33 @@ export default class Router {
|
||||
private getRoute(request: RouterRequest): Route | undefined {
|
||||
const url = new URL(request.url)
|
||||
const pathArr = url.pathname.split('/').filter(i => i)
|
||||
|
||||
return this.routes.find(r => {
|
||||
const routeArr = r.url.split('/').filter(i => i)
|
||||
|
||||
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
|
||||
return false
|
||||
|
||||
const params: RouterRequestParams = {}
|
||||
|
||||
for (let i = 0; i < routeArr.length; i++) {
|
||||
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
|
||||
return false
|
||||
|
||||
if (routeArr[i][0] === ':')
|
||||
params[routeArr[i].substring(1)] = pathArr[i]
|
||||
}
|
||||
|
||||
request.params = params
|
||||
|
||||
const query: any = {}
|
||||
|
||||
for (const [k, v] of url.searchParams.entries()) {
|
||||
query[k] = v
|
||||
}
|
||||
|
||||
request.query = query
|
||||
|
||||
return true
|
||||
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
|
||||
}
|
||||
@@ -371,9 +391,9 @@ export default class Router {
|
||||
* @param {any} env
|
||||
* @param {Request} request
|
||||
* @param {any} [extend]
|
||||
* @returns {Response}
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
public async handle(env: any, request: Request, extend: any = {}) {
|
||||
public async handle(env: any, request: Request, extend: any = {}): Promise<Response> {
|
||||
try {
|
||||
const req: RouterRequest = {
|
||||
...extend,
|
||||
@@ -387,22 +407,29 @@ export default class Router {
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
const route = this.getRoute(req)
|
||||
|
||||
if (this.corsConfig.allowOrigin)
|
||||
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||
if (this.corsConfig.allowMethods)
|
||||
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||
if (this.corsConfig.allowHeaders)
|
||||
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||
if (this.corsConfig.maxAge)
|
||||
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||
if (this.corsEnabled) {
|
||||
if (this.corsConfig.allowOrigin)
|
||||
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||
if (this.corsConfig.allowMethods)
|
||||
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||
if (this.corsConfig.allowHeaders)
|
||||
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||
if (this.corsConfig.maxAge)
|
||||
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers,
|
||||
status: this.corsConfig.optionsSuccessStatus
|
||||
})
|
||||
if (!route && req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers,
|
||||
status: this.corsConfig.optionsSuccessStatus
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
|
||||
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
||||
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
|
||||
try {
|
||||
@@ -418,27 +445,33 @@ export default class Router {
|
||||
}
|
||||
}
|
||||
}
|
||||
const route = this.getRoute(req)
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
|
||||
const res: RouterResponse = { headers }
|
||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||
let prevIndex = -1
|
||||
|
||||
const runner = async (index: number) => {
|
||||
if (index === prevIndex)
|
||||
throw new Error('next() called multiple times')
|
||||
|
||||
prevIndex = index
|
||||
|
||||
if (typeof handlers[index] === 'function')
|
||||
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
|
||||
}
|
||||
|
||||
await runner(0)
|
||||
|
||||
if (typeof res.body === 'object') {
|
||||
if (!res.headers.has('Content-Type'))
|
||||
res.headers.set('Content-Type', 'application/json')
|
||||
|
||||
res.body = JSON.stringify(res.body)
|
||||
}
|
||||
|
||||
if (res.raw)
|
||||
return res.raw
|
||||
|
||||
return new Response([101, 204, 205, 304].includes(res.status || (res.body ? 200 : 204)) ? null : res.body, { status: res.status, headers: res.headers, webSocket: res.webSocket || null })
|
||||
} catch(err) {
|
||||
console.error(err)
|
||||
|
||||
Reference in New Issue
Block a user