Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
5fa3475a20
|
|||
|
0637549e90
|
|||
|
f3279e71fc
|
|||
|
bdb7be3699
|
|||
|
45a781ea66
|
|||
|
7f44f304a2
|
|||
|
a786262ec6
|
|||
|
8e58dc349e
|
|||
|
e94e84a742
|
|||
|
b16a56bbca
|
|||
|
6f84645f89
|
|||
|
53f8365993
|
18
README.md
18
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
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.0.1",
|
||||
"version": "2.1.2",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.0.1",
|
||||
"version": "2.1.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "2.0.1",
|
||||
"version": "2.1.2",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
|
||||
137
src/index.ts
137
src/index.ts
@@ -6,7 +6,7 @@
|
||||
* @property {string} url URL String
|
||||
* @property {RouterHandler[]} handlers Array of handler functions
|
||||
*/
|
||||
interface Route {
|
||||
export interface Route {
|
||||
method: string
|
||||
url: string
|
||||
handlers: RouterHandler[]
|
||||
@@ -16,12 +16,12 @@
|
||||
* Router Context
|
||||
*
|
||||
* @typedef RouterContext
|
||||
* @property {Object<string, string>} env Environment
|
||||
* @property {RouterEnv} env Environment
|
||||
* @property {RouterRequest} req Request Object
|
||||
* @property {RouterResponse} res Response Object
|
||||
* @property {RouterNext} next Next Handler
|
||||
*/
|
||||
interface RouterContext {
|
||||
export interface RouterContext {
|
||||
env: any
|
||||
req: RouterRequest
|
||||
res: RouterResponse
|
||||
@@ -37,17 +37,18 @@ interface RouterContext {
|
||||
* @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 {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 {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 {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
|
||||
*/
|
||||
interface RouterRequest {
|
||||
export interface RouterRequest {
|
||||
url: string
|
||||
method: string
|
||||
params: RouterRequestParams
|
||||
query: RouterRequestQuery
|
||||
headers: Headers
|
||||
body: any
|
||||
body: string | any
|
||||
cf?: IncomingRequestCfProperties
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,7 +56,7 @@ interface RouterRequest {
|
||||
*
|
||||
* @typedef RouterRequestParams
|
||||
*/
|
||||
interface RouterRequestParams {
|
||||
export interface RouterRequestParams {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ interface RouterRequestParams {
|
||||
*
|
||||
* @typedef RouterRequestQuery
|
||||
*/
|
||||
interface RouterRequestQuery {
|
||||
export interface RouterRequestQuery {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -74,13 +75,13 @@ interface RouterRequestQuery {
|
||||
* @typedef RouterResponse
|
||||
* @property {Headers} headers Response headers object
|
||||
* @property {number} [status=204] Return status code (default: `204`)
|
||||
* @property {any} [body] Either an `object` (will be converted to JSON) or a string
|
||||
* @property {string | any} [body] Either an `object` (will be converted to JSON) or a string
|
||||
* @property {Response} [raw] A response object that is to be returned, this will void all other res properties and return this as is.
|
||||
*/
|
||||
interface RouterResponse {
|
||||
export interface RouterResponse {
|
||||
headers: Headers
|
||||
status?: number
|
||||
body?: any
|
||||
body?: string | any
|
||||
raw?: Response,
|
||||
webSocket?: WebSocket
|
||||
}
|
||||
@@ -89,9 +90,9 @@ interface RouterResponse {
|
||||
* Next Function
|
||||
*
|
||||
* @callback RouterNext
|
||||
* @returns {Promise}
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
interface RouterNext {
|
||||
export interface RouterNext {
|
||||
(): Promise<void>
|
||||
}
|
||||
|
||||
@@ -102,7 +103,7 @@ interface RouterNext {
|
||||
* @param {RouterContext} ctx
|
||||
* @returns {Promise<void> | void}
|
||||
*/
|
||||
interface RouterHandler {
|
||||
export interface RouterHandler {
|
||||
(ctx: RouterContext): Promise<void> | void
|
||||
}
|
||||
|
||||
@@ -116,22 +117,21 @@ interface RouterHandler {
|
||||
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
||||
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||
*/
|
||||
interface RouterCorsConfig {
|
||||
allowOrigin: string
|
||||
allowMethods: string
|
||||
allowHeaders: string
|
||||
maxAge: number
|
||||
optionsSuccessStatus: number
|
||||
export interface RouterCorsConfig {
|
||||
allowOrigin?: string
|
||||
allowMethods?: string
|
||||
allowHeaders?: string
|
||||
maxAge?: number
|
||||
optionsSuccessStatus?: number
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Router
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
*/
|
||||
class Router {
|
||||
export default class Router {
|
||||
|
||||
/**
|
||||
* Router Array
|
||||
@@ -143,6 +143,9 @@ class Router {
|
||||
|
||||
/**
|
||||
* Global Handlers
|
||||
*
|
||||
* @protected
|
||||
* @type {RouterHandler[]}
|
||||
*/
|
||||
protected globalHandlers: RouterHandler[] = []
|
||||
|
||||
@@ -160,13 +163,15 @@ class Router {
|
||||
* @protected
|
||||
* @type {RouterCorsConfig}
|
||||
*/
|
||||
protected corsConfig: RouterCorsConfig = {
|
||||
allowOrigin: '*',
|
||||
allowMethods: '*',
|
||||
allowHeaders: '*',
|
||||
maxAge: 86400,
|
||||
optionsSuccessStatus: 204
|
||||
}
|
||||
protected corsConfig: RouterCorsConfig = {}
|
||||
|
||||
/**
|
||||
* CORS enabled
|
||||
*-
|
||||
* @protected
|
||||
* @type {boolean}
|
||||
*/
|
||||
protected corsEnabled: boolean = false
|
||||
|
||||
/**
|
||||
* Register global handlers
|
||||
@@ -297,7 +302,7 @@ class Router {
|
||||
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
|
||||
* @returns {Router}
|
||||
*/
|
||||
public debug(state = true): Router {
|
||||
public debug(state: boolean = true): Router {
|
||||
this.debugMode = state
|
||||
return this
|
||||
}
|
||||
@@ -309,10 +314,11 @@ 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
|
||||
}
|
||||
@@ -334,6 +340,7 @@ class Router {
|
||||
url,
|
||||
handlers
|
||||
})
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
@@ -341,29 +348,39 @@ class Router {
|
||||
* Get Route by request
|
||||
*
|
||||
* @private
|
||||
* @param {Request} request
|
||||
* @returns {RouterRequest | undefined}
|
||||
* @param {RouterRequest} request
|
||||
* @returns {Route | undefined}
|
||||
*/
|
||||
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))
|
||||
}
|
||||
@@ -374,9 +391,9 @@ 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,
|
||||
@@ -388,17 +405,31 @@ class Router {
|
||||
query: {},
|
||||
body: ''
|
||||
}
|
||||
if (req.method === 'OPTIONS' && Object.keys(this.corsConfig).length) {
|
||||
|
||||
const headers = new Headers()
|
||||
const route = this.getRoute(req)
|
||||
|
||||
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 (!route && req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': this.corsConfig.allowOrigin,
|
||||
'Access-Control-Allow-Methods': this.corsConfig.allowMethods,
|
||||
'Access-Control-Allow-Headers': this.corsConfig.allowHeaders,
|
||||
'Access-Control-Max-Age': this.corsConfig.maxAge!.toString()
|
||||
},
|
||||
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 {
|
||||
@@ -414,33 +445,33 @@ class Router {
|
||||
}
|
||||
}
|
||||
}
|
||||
const route = this.getRoute(req)
|
||||
if (!route)
|
||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||
const res: RouterResponse = { headers: new Headers() }
|
||||
if (Object.keys(this.corsConfig).length) {
|
||||
res.headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
|
||||
res.headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
|
||||
res.headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
|
||||
res.headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -448,5 +479,3 @@ class Router {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Router
|
||||
|
||||
Reference in New Issue
Block a user