1
0

6 Commits

Author SHA1 Message Date
a4fd646d6b remove connect and trace methods 2024-01-20 02:15:34 +01:00
606d5f1cb2 clean up 2023-11-16 22:38:51 +01:00
95ccb2263a 3.1.3 2023-11-14 14:54:46 +01:00
dc88d900cb fix default extension types 2023-11-14 14:54:04 +01:00
0dca90f4f9 3.1.2 2023-11-12 18:52:30 +01:00
cb8724edc4 clean up 2023-11-12 18:48:49 +01:00
5 changed files with 104 additions and 71 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

@@ -33,6 +33,10 @@ Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
```typescript
import { Router } from '@tsndr/cloudflare-worker-router'
// 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
@@ -43,11 +47,23 @@ export type 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()
@@ -289,6 +305,10 @@ npm i -D @tsndr/cloudflare-worker-router
```typescript
import { Router } from '@tsndr/cloudflare-worker-router'
// 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
@@ -298,32 +318,57 @@ export type 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', async () => {
// return new Response('Hello World')
//})
// return new Response('Hello World')
// })
/// Example Route for splitting into multiple files
//
// const hiHandler: RouteHandler<Env> = async () => {
// const helloHandler: Handler = async () => {
// return new Response('Hello World')
// }
//
// router.get('/hi', hiHandler)
// router.get('/hellow', helloHandler)
// TODO: add your routes here
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
return router.handle(request, env, ctx)
}
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
return router.handle(request, env, ctx)
}
}
```
@@ -338,6 +383,12 @@ import { Router } from '@tsndr/cloudflare-worker-router'
const router = new Router()
// Enable Debug Mode
//router.debug()
// Enabling build in CORS support
//router.cors()
/// Example Route
//
// router.get('/hi', async () => {

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.1.1",
"version": "3.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@tsndr/cloudflare-worker-router",
"version": "3.1.1",
"version": "3.1.3",
"license": "MIT",
"devDependencies": {
"@cloudflare/workers-types": "^4.20231025.0",

View File

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

View File

@@ -6,10 +6,10 @@
* @property {string} url URL String
* @property {RouterHandler[]} handlers Array of handler functions
*/
export type Route<TEnv, TCtx, TReq> = {
export type Route<Env, CtxExt, ReqExt> = {
method: 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 {ExecutionContext} ctx Context Object
*/
export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
env: TEnv
req: RouterRequest<TReq>
export type RouterContext<Env = any, CtxExt = {}, ReqExt = {}> = CtxExt & {
env: Env
req: RouterRequest<ReqExt>
dbg: boolean
ctx?: ExecutionContext
}
@@ -39,7 +39,7 @@ export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
* @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 type RouterRequest<TReq> = TReq & {
export type RouterRequest<ReqExt> = ReqExt & {
url: string
method: string
params: RouterRequestParams
@@ -51,7 +51,7 @@ export type RouterRequest<TReq> = TReq & {
json<T>(): Promise<T>
formData(): Promise<FormData>
blob(): Promise<Blob>
bearer: () => string | undefined
bearer(): string | undefined
cf?: IncomingRequestCfProperties
}
@@ -80,8 +80,8 @@ export type RouterRequestQuery = {
* @param {RouterContext} ctx
* @returns {Promise<Response | void> Response | void}
*/
export type RouterHandler<TEnv = any, TCtx = any, TReq = any> = {
(ctx: RouterContext<TEnv, TCtx, TReq>): Promise<Response | void> | Response | void
export type RouterHandler<Env = any, CtxExt = {}, ReqExt = {}> = {
(ctx: RouterContext<Env, CtxExt, ReqExt>): Promise<Response | void> | Response | void
}
/**
@@ -120,7 +120,7 @@ export type RouterBuffer = {
* @public
* @class
*/
export class Router<TEnv = any, TCtx = any, TReq = any> {
export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
/**
* Router Array
@@ -128,7 +128,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @protected
* @type {Route[]}
*/
protected routes: Route<TEnv, TCtx, TReq>[] = []
protected routes: Route<Env, CtxExt, ReqExt>[] = []
/**
* Global Handlers
@@ -136,7 +136,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @protected
* @type {RouterHandler[]}
*/
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
protected globalHandlers: RouterHandler<Env, CtxExt, ReqExt>[] = []
/**
* Debug Mode
@@ -168,24 +168,13 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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) {
this.globalHandlers.push(handler)
}
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
*
@@ -193,7 +182,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -204,7 +193,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -215,7 +204,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -226,7 +215,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -237,7 +226,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -248,7 +237,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -259,21 +248,10 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
/**
* 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
*
@@ -281,7 +259,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers
* @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)
}
@@ -291,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)
* @returns {Router}
*/
public debug(state: boolean = true): Router<TEnv, TCtx, TReq> {
public debug(state: boolean = true): Router<Env, CtxExt, ReqExt> {
this.debugMode = state
return this
}
@@ -302,7 +280,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterCorsConfig} [config]
* @returns {Router}
*/
public cors(config?: RouterCorsConfig): Router<TEnv, TCtx, TReq> {
public cors(config?: RouterCorsConfig): Router<Env, CtxExt, ReqExt> {
this.corsEnabled = true
this.corsConfig = {
allowOrigin: config?.allowOrigin ?? '*',
@@ -341,7 +319,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterHandler[]} handlers Arrar of handler functions
* @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({
method,
url,
@@ -358,7 +336,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* @param {RouterRequest} request
* @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 pathArr = url.pathname.split('/').filter(i => i)
@@ -396,15 +374,15 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
* Handle requests
*
* @param {Request} request
* @param {TEnv} env
* @param {TCtx} [extCtx]
* @param {TReq} [extReq]
* @param {Env} env
* @param {CtxExt} [ctxExt]
* @param {ReqExt} [reqExt]
* @returns {Promise<Response>}
*/
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extCtx?: TCtx, extReq?: TReq): Promise<Response> {
const buffer: RouterBuffer = {};
public async handle(request: Request, env: Env, ctx?: ExecutionContext, ctxExt?: CtxExt, reqExt?: ReqExt): Promise<Response> {
const buffer: RouterBuffer = {}
const req = {
...(extReq ?? {}),
...(reqExt ?? {}),
method: request.method,
headers: request.headers,
url: request.url,
@@ -418,7 +396,7 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
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>
} as RouterRequest<ReqExt>
if (this.corsEnabled && req.method === 'OPTIONS') {
return new Response(null, {
@@ -439,12 +417,12 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
for (const handler of handlers) {
const context = {
...(extCtx ?? {}),
...(ctxExt ?? {}),
env,
req,
dbg,
ctx
} as RouterContext<TEnv, TCtx, TReq>
} as RouterContext<Env, CtxExt, ReqExt>
const res = await handler(context)