1
0

5 Commits

Author SHA1 Message Date
8e58dc349e 2.1.0 2022-09-29 18:56:02 +02:00
e94e84a742 fix cors always on issue 2022-09-29 18:48:23 +02:00
b16a56bbca minor type fixes 2022-07-19 18:51:31 +02:00
6f84645f89 2.0.2 2022-07-19 15:08:19 +02:00
53f8365993 add types 2022-06-28 12:04:45 +02:00
3 changed files with 47 additions and 51 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "2.0.1",
"version": "2.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@tsndr/cloudflare-worker-router",
"version": "2.0.1",
"version": "2.1.0",
"license": "MIT",
"devDependencies": {
"@cloudflare/workers-types": "^3.13.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "2.0.1",
"version": "2.1.0",
"description": "",
"main": "index.js",
"types": "index.d.ts",

View File

@@ -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,7 @@ class Router {
* @protected
* @type {RouterCorsConfig}
*/
protected corsConfig: RouterCorsConfig = {
allowOrigin: '*',
allowMethods: '*',
allowHeaders: '*',
maxAge: 86400,
optionsSuccessStatus: 204
}
protected corsConfig: RouterCorsConfig = {}
/**
* Register global handlers
@@ -297,7 +294,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
}
@@ -341,8 +338,8 @@ 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)
@@ -388,14 +385,21 @@ class Router {
query: {},
body: ''
}
if (req.method === 'OPTIONS' && Object.keys(this.corsConfig).length) {
const headers = new Headers()
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: {
'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
})
}
@@ -417,13 +421,7 @@ 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) => {
@@ -448,5 +446,3 @@ class Router {
}
}
}
export default Router