1
0

15 Commits

Author SHA1 Message Date
c2b6189a86 3.0.0-8 2023-02-02 20:53:11 +01:00
33cafbf17c update replace to be case insensitive 2023-02-02 20:53:02 +01:00
1e78778ba0 3.0.0-7 2023-02-02 20:38:45 +01:00
b0d05656bb add bearer helper function 2023-02-02 20:37:58 +01:00
d4ba12a517 update readme 2023-02-02 19:03:18 +01:00
b48e5c2333 clean up 2023-02-02 18:51:12 +01:00
bf41e2c193 update readme 2023-02-02 18:48:20 +01:00
5342cfd310 update dev dependencies 2023-02-02 18:43:36 +01:00
8f400ff5b7 3.0.0-6 2023-02-02 18:38:37 +01:00
51f30f642f clean up 2023-02-02 18:37:45 +01:00
bcab122e15 add dbg to handler context 2023-02-02 18:37:28 +01:00
f3181ca9a5 change || to ?? 2023-02-02 18:31:33 +01:00
7edfc835fa change interfaces to types 2023-02-02 18:30:03 +01:00
7300e36469 update migration guide 2023-02-02 18:08:49 +01:00
e122feadb5 update readmes 2023-02-02 17:40:28 +01:00
5 changed files with 123 additions and 114 deletions

View File

@@ -1,71 +1,70 @@
# Migration Guide # Migration Guide
From `v1.x.x` to `v2.x.x`. From `v2.x.x` to `v3.x.x`.
## Contents ## Contents
- [Preparation](#preparation) - [Update Router](#update-router)
- [Update](#update) - [Handlers](#handlers)
- [Import / Require](#import--require)
- [Routes](#routes)
- [Fetch](#fetch--routerhandle) - [Fetch](#fetch--routerhandle)
## Preparation ## Update Router
Follow Cloudflare's [Migration Guide](https://developers.cloudflare.com/workers/wrangler/migration/migrating-from-wrangler-1/) to update your protject to [wrangler2](https://github.com/cloudflare/wrangler2). Update to the latest version version of the router.
## Update
Update to the latest version verstion
```bash ```bash
npm i -D @tsndr/cloudflare-worker-router npm i -D @tsndr/cloudflare-worker-router
``` ```
## Import / Require
Switch to ESModules. ## Handlers
- Remove `res` and `next` from handler parameter list.
- Replace `res.` with `return new Response()` / `return Response.json()`.
- Remove `next()` calls from middlewares.
### Before ### Before
```javascript ```typescript
const Router = require('@tsndr/cloudflare-worker-router') // Register global middleware
router.use(({ env, req, res, next }) => {
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
res.status = 401
return
}
next()
})
// Simple get
router.get('/user', ({ res }) => {
res.body = {
id: 1,
name: 'John Doe'
}
})
``` ```
### After ### After
```javascript ```typescript
import Router from '@tsndr/cloudflare-worker-router' // Register global middleware
router.use(({ env, req }) => {
// Intercept if token doesn't match
if (req.headers.get('authorization') !== env.SECRET_TOKEN) {
return new Response(null, { status: 401 })
}
})
// Simple get
router.get('/user', () => {
return Response.json({
id: 1,
name: 'John Doe'
})
})
``` ```
## Routes
Just add curly braces.
### Before
<a href="https://gist.github.com/tsndr/34e8544266ae15d51abd019d7c3d27ca" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 57 01 PM" src="https://user-images.githubusercontent.com/2940127/175572731-a8729c1b-15e2-45ac-be80-7e8527c5502a.png"></a>
### After
<a href="https://gist.github.com/tsndr/8db6e8dd55e348015c2ff8e93dd6aa31" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 55 56 PM" src="https://user-images.githubusercontent.com/2940127/175572549-0eea8fc4-3d90-412a-89cc-d2f4569f1139.png"></a>
## Fetch / `router.handle()`
❗️ Be aware that with `v2.0.0` the parameters of `router.handle()` changed ❗️
### Before
<a href="https://gist.github.com/tsndr/12b0f800269760c597646c90a562ef88" target="_blank"><img width="469" alt="Petrify 2022-06-24 at 5 58 43 PM" src="https://user-images.githubusercontent.com/2940127/175572993-fb4681c2-eece-4c92-88e8-1c2f57644769.png"></a>
### After
<a href="https://gist.github.com/tsndr/30902b01b134e2a58cf3a53648dd3e47" target="_blank"><img width="393" alt="Petrify 2022-06-24 at 5 59 22 PM" src="https://user-images.githubusercontent.com/2940127/175573110-b7dfcfb2-855d-4529-a957-6f8b9ec439f3.png"></a>

View File

@@ -12,7 +12,7 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
- [Features](#features) - [Features](#features)
- [Usage](#usage) - [Usage](#usage)
- [Reference](#reference) - [Reference](#reference)
- [Setup](#setup) - [Getting started](#getting-started)
## Features ## Features
@@ -26,12 +26,14 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
## Usage ## Usage
Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
### TypeScript Example ### TypeScript Example
```typescript ```typescript
import { Router } from '@tsndr/cloudflare-worker-router' import { Router } from '@tsndr/cloudflare-worker-router'
export interface 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
// //
@@ -51,12 +53,10 @@ const router = new Router<Env>()
router.cors() router.cors()
// Register global middleware // Register global middleware
router.use(() => { router.use(({ env, req }) => {
return new Response(null, { // Intercept if token doesn't match
headers: { if (req.headers.get('authorization') !== env.SECRET_TOKEN)
'X-Global-Middlewares': 'true' return new Response(null, { status: 401 })
}
})
}) })
// Simple get // Simple get
@@ -85,9 +85,7 @@ router.post('/user/:id', ({ req }) => {
// Delete route using a middleware // Delete route using a middleware
router.delete('/user/:id', ({ env, req }) => { router.delete('/user/:id', ({ env, req }) => {
const { SECRET_TOKEN } = env if (req.headers.get('authorization') === env.SECRET_TOKEN)
if (req.headers.get('Authorization') === SECRET_TOKEN)
return new Response(null, { status: 401 }) return new Response(null, { status: 401 })
}, ({ req }) => { }, ({ req }) => {
@@ -121,12 +119,10 @@ const router = new Router()
router.cors() router.cors()
// Register global middleware // Register global middleware
router.use(() => { router.use(({ env, req }) => {
return new Response(null, { // Intercept if token doesn't match
headers: { if (req.headers.get('authorization') !== env.SECRET_TOKEN)
'X-Global-Middlewares': 'true' return new Response(null, { status: 401 })
}
})
}) })
// Simple get // Simple get
@@ -139,11 +135,12 @@ router.get('/user', () => {
// Post route with url parameter // Post route with url parameter
router.post('/user/:id', ({ req }) => { router.post('/user/:id', ({ req }) => {
const userId = req.params.id const userId = req.params.id
// Do stuff // Do stuff
if (errorDoingStuff) { if (!true) {
return Response.json({ return Response.json({
error: 'Error doing stuff!' error: 'Error doing stuff!'
}, { status: 400 }) }, { status: 400 })
@@ -154,17 +151,16 @@ router.post('/user/:id', ({ req }) => {
// Delete route using a middleware // Delete route using a middleware
router.delete('/user/:id', ({ env, req }) => { router.delete('/user/:id', ({ env, req }) => {
const { SECRET_TOKEN } = env if (req.headers.get('authorization') === env.SECRET_TOKEN)
if (req.headers.get('Authorization') === SECRET_TOKEN)
return new Response(null, { status: 401 }) return new Response(null, { status: 401 })
}, ({ req }) => { }, ({ req }) => {
const userId = req.params.id
// Do stuff... const userId = req.params.id
return Response.json({ userId }) // Do stuff...
return Response.json({ userId })
}) })
// Listen Cloudflare Workers Fetch Event // Listen Cloudflare Workers Fetch Event
@@ -268,7 +264,7 @@ Key | Type | Description
`query` | `object` | Object containing all query parameters `query` | `object` | Object containing all query parameters
## Setup ## Getting started
Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler. Please follow Cloudflare's [Get started guide](https://developers.cloudflare.com/workers/get-started/guide/) to install wrangler.
@@ -291,7 +287,7 @@ npm i -D @tsndr/cloudflare-worker-router
```typescript ```typescript
import { Router } from '@tsndr/cloudflare-worker-router' import { Router } from '@tsndr/cloudflare-worker-router'
export interface 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
// //
@@ -306,15 +302,15 @@ const router = new Router<Env>()
/// Example Route /// Example Route
// //
// router.get(/'hi', ({ res }) => { // router.get('/hi', async () => {
// res.body = '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> = ({ res }) => { // const hiHandler: RouteHandler<Env> = async () => {
// res.body = 'Hello World' // return new Response('Hello World')
// } // }
// //
// router.get('/hi', hiHandler) // router.get('/hi', hiHandler)
@@ -340,9 +336,19 @@ import { Router } from '@tsndr/cloudflare-worker-router'
const router = new Router() const router = new Router()
// router.get(/'hi', ({ res }) => { /// Example Route
// res.body = 'Hello World' //
//} // router.get('/hi', async () => {
// return new Response('Hello World')
//})
/// Example Route for splitting into multiple files
//
// async function hiHandler() {
// return new Response('Hello World')
// }
//
// router.get('/hi', hiHandler)
// TODO: add your routes here // TODO: add your routes here

32
package-lock.json generated
View File

@@ -1,28 +1,28 @@
{ {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-5", "version": "3.0.0-8",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-5", "version": "3.0.0-8",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^4.20230115.0",
"typescript": "^4.7.4" "typescript": "^4.9.5"
} }
}, },
"node_modules/@cloudflare/workers-types": { "node_modules/@cloudflare/workers-types": {
"version": "3.13.0", "version": "4.20230115.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz", "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==", "integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
"dev": true "dev": true
}, },
"node_modules/typescript": { "node_modules/typescript": {
"version": "4.7.4", "version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true, "dev": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
@@ -35,15 +35,15 @@
}, },
"dependencies": { "dependencies": {
"@cloudflare/workers-types": { "@cloudflare/workers-types": {
"version": "3.13.0", "version": "4.20230115.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-3.13.0.tgz", "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
"integrity": "sha512-oyhzfYlWBLgd9odJ/WHcsD/8B+IaAjSD+OcPEGLzX5kGRONjwcW3NY0WQfsVIhQzZ6AbPzjwkmj4D2VFwU1xRQ==", "integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
"dev": true "dev": true
}, },
"typescript": { "typescript": {
"version": "4.7.4", "version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true "dev": true
} }
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-router", "name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-5", "version": "3.0.0-8",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
@@ -31,7 +31,7 @@
}, },
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme", "homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^4.20230115.0",
"typescript": "^4.7.4" "typescript": "^4.9.5"
} }
} }

View File

@@ -6,7 +6,7 @@
* @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 interface Route<TEnv, TExt> { export type Route<TEnv, TExt> = {
method: string method: string
url: string url: string
handlers: RouterHandler<TEnv, TExt>[] handlers: RouterHandler<TEnv, TExt>[]
@@ -20,9 +20,10 @@ export interface Route<TEnv, TExt> {
* @property {RouterRequest} req Request Object * @property {RouterRequest} req Request Object
* @property {ExecutionContext} ctx Context Object * @property {ExecutionContext} ctx Context Object
*/ */
export interface RouterContext<TEnv = any, TExt = any> { export type RouterContext<TEnv = any, TExt = any> = {
env: TEnv env: TEnv
req: RouterRequest<TExt> req: RouterRequest<TExt>
dbg: boolean
ctx?: ExecutionContext ctx?: ExecutionContext
} }
@@ -47,6 +48,7 @@ export type RouterRequest<TExt> = {
body: string | any body: string | any
raw: Request raw: Request
cf?: IncomingRequestCfProperties cf?: IncomingRequestCfProperties
bearer: () => string
} & TExt } & TExt
/** /**
@@ -54,7 +56,7 @@ export type RouterRequest<TExt> = {
* *
* @typedef RouterRequestParams * @typedef RouterRequestParams
*/ */
export interface RouterRequestParams { export type RouterRequestParams = {
[key: string]: string [key: string]: string
} }
@@ -63,7 +65,7 @@ export interface RouterRequestParams {
* *
* @typedef RouterRequestQuery * @typedef RouterRequestQuery
*/ */
export interface RouterRequestQuery { export type RouterRequestQuery = {
[key: string]: string [key: string]: string
} }
@@ -74,7 +76,7 @@ export interface RouterRequestQuery {
* @param {RouterContext} ctx * @param {RouterContext} ctx
* @returns {Promise<Response | void> Response | void} * @returns {Promise<Response | void> Response | void}
*/ */
export interface RouterHandler<TEnv = any, TExt = any> { export type RouterHandler<TEnv = any, TExt = any> = {
(ctx: RouterContext<TEnv, TExt>): Promise<Response | void> | Response | void (ctx: RouterContext<TEnv, TExt>): Promise<Response | void> | Response | void
} }
@@ -88,7 +90,7 @@ export interface RouterHandler<TEnv = any, TExt = any> {
* @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`)
*/ */
export interface RouterCorsConfig { export type RouterCorsConfig = {
allowOrigin?: string allowOrigin?: string
allowMethods?: string allowMethods?: string
allowHeaders?: string allowHeaders?: string
@@ -287,11 +289,11 @@ export class Router<TEnv = any, TExt = any> {
public cors(config?: RouterCorsConfig): Router<TEnv, TExt> { public cors(config?: RouterCorsConfig): Router<TEnv, TExt> {
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 ?? '*',
maxAge: config?.maxAge || 86400, maxAge: config?.maxAge ?? 86400,
optionsSuccessStatus: config?.optionsSuccessStatus || 204 optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
} }
return this return this
} }
@@ -371,8 +373,8 @@ export class Router<TEnv = any, TExt = any> {
/** /**
* Handle requests * Handle requests
* *
* @param {TEnv} env
* @param {Request} request * @param {Request} request
* @param {TEnv} env
* @param {TExt} [ext] * @param {TExt} [ext]
* @returns {Promise<Response>} * @returns {Promise<Response>}
*/ */
@@ -386,7 +388,8 @@ export class Router<TEnv = any, TExt = any> {
raw: request, raw: request,
params: {}, params: {},
query: {}, query: {},
body: '' body: '',
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim() ?? '',
} as RouterRequest<TExt> } as RouterRequest<TExt>
const route = this.getRoute(req) const route = this.getRoute(req)
@@ -402,11 +405,12 @@ export class Router<TEnv = any, TExt = any> {
} }
const handlers = [...this.globalHandlers, ...route.handlers] const handlers = [...this.globalHandlers, ...route.handlers]
const dbg = this.debugMode
let response: Response | undefined let response: Response | undefined
for (const handler of handlers) { for (const handler of handlers) {
const res = await handler({ env, req, ctx }) const res = await handler({ env, req, dbg, ctx })
if (res) { if (res) {
response = res response = res