Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
8f400ff5b7
|
|||
|
51f30f642f
|
|||
|
bcab122e15
|
|||
|
f3181ca9a5
|
|||
|
7edfc835fa
|
|||
|
7300e36469
|
|||
|
e122feadb5
|
93
MIGRATION.md
93
MIGRATION.md
@@ -1,71 +1,70 @@
|
||||
# Migration Guide
|
||||
|
||||
From `v1.x.x` to `v2.x.x`.
|
||||
From `v2.x.x` to `v3.x.x`.
|
||||
|
||||
|
||||
## Contents
|
||||
|
||||
- [Preparation](#preparation)
|
||||
- [Update](#update)
|
||||
- [Import / Require](#import--require)
|
||||
- [Routes](#routes)
|
||||
- [Update Router](#update-router)
|
||||
- [Handlers](#handlers)
|
||||
- [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
|
||||
|
||||
Update to the latest version verstion
|
||||
Update to the latest version version of the router.
|
||||
|
||||
```bash
|
||||
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
|
||||
|
||||
```javascript
|
||||
const Router = require('@tsndr/cloudflare-worker-router')
|
||||
```typescript
|
||||
// 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
|
||||
|
||||
```javascript
|
||||
import Router from '@tsndr/cloudflare-worker-router'
|
||||
```typescript
|
||||
// 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>
|
||||
|
||||
56
README.md
56
README.md
@@ -26,6 +26,8 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
||||
|
||||
## Usage
|
||||
|
||||
Migrating from `v2.x.x`, check out the [Migration Guide](MIGRATION.md).
|
||||
|
||||
### TypeScript Example
|
||||
|
||||
```typescript
|
||||
@@ -51,12 +53,10 @@ const router = new Router<Env>()
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
router.use(() => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'X-Global-Middlewares': 'true'
|
||||
}
|
||||
})
|
||||
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
|
||||
@@ -85,9 +85,7 @@ router.post('/user/:id', ({ req }) => {
|
||||
|
||||
// Delete route using a middleware
|
||||
router.delete('/user/:id', ({ env, req }) => {
|
||||
const { SECRET_TOKEN } = env
|
||||
|
||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
|
||||
}, ({ req }) => {
|
||||
@@ -121,12 +119,10 @@ const router = new Router()
|
||||
router.cors()
|
||||
|
||||
// Register global middleware
|
||||
router.use(() => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
'X-Global-Middlewares': 'true'
|
||||
}
|
||||
})
|
||||
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
|
||||
@@ -139,11 +135,12 @@ router.get('/user', () => {
|
||||
|
||||
// Post route with url parameter
|
||||
router.post('/user/:id', ({ req }) => {
|
||||
|
||||
const userId = req.params.id
|
||||
|
||||
// Do stuff
|
||||
|
||||
if (errorDoingStuff) {
|
||||
if (!true) {
|
||||
return Response.json({
|
||||
error: 'Error doing stuff!'
|
||||
}, { status: 400 })
|
||||
@@ -154,12 +151,11 @@ router.post('/user/:id', ({ req }) => {
|
||||
|
||||
// Delete route using a middleware
|
||||
router.delete('/user/:id', ({ env, req }) => {
|
||||
const { SECRET_TOKEN } = env
|
||||
|
||||
if (req.headers.get('Authorization') === SECRET_TOKEN)
|
||||
if (req.headers.get('authorization') === env.SECRET_TOKEN)
|
||||
return new Response(null, { status: 401 })
|
||||
|
||||
}, ({ req }) => {
|
||||
|
||||
const userId = req.params.id
|
||||
|
||||
// Do stuff...
|
||||
@@ -306,15 +302,15 @@ const router = new Router<Env>()
|
||||
|
||||
/// Example Route
|
||||
//
|
||||
// router.get(/'hi', ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
// router.get(/'hi', async () => {
|
||||
// return new Response('Hello World')
|
||||
//}
|
||||
|
||||
|
||||
/// Example Route for splitting into multiple files
|
||||
//
|
||||
// const hiHandler: RouteHandler<Env> = ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
// const hiHandler: RouteHandler<Env> = async () => {
|
||||
// return new Response('Hello World')
|
||||
// }
|
||||
//
|
||||
// router.get('/hi', hiHandler)
|
||||
@@ -340,10 +336,20 @@ import { Router } from '@tsndr/cloudflare-worker-router'
|
||||
|
||||
const router = new Router()
|
||||
|
||||
// router.get(/'hi', ({ res }) => {
|
||||
// res.body = 'Hello World'
|
||||
/// Example Route
|
||||
//
|
||||
// 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
|
||||
|
||||
export default {
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-5",
|
||||
"version": "3.0.0-6",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-5",
|
||||
"version": "3.0.0-6",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-router",
|
||||
"version": "3.0.0-5",
|
||||
"version": "3.0.0-6",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
|
||||
28
src/index.ts
28
src/index.ts
@@ -6,7 +6,7 @@
|
||||
* @property {string} url URL String
|
||||
* @property {RouterHandler[]} handlers Array of handler functions
|
||||
*/
|
||||
export interface Route<TEnv, TExt> {
|
||||
export type Route<TEnv, TExt> = {
|
||||
method: string
|
||||
url: string
|
||||
handlers: RouterHandler<TEnv, TExt>[]
|
||||
@@ -20,9 +20,10 @@ export interface Route<TEnv, TExt> {
|
||||
* @property {RouterRequest} req Request Object
|
||||
* @property {ExecutionContext} ctx Context Object
|
||||
*/
|
||||
export interface RouterContext<TEnv = any, TExt = any> {
|
||||
export type RouterContext<TEnv = any, TExt = any> = {
|
||||
env: TEnv
|
||||
req: RouterRequest<TExt>
|
||||
dbg: boolean
|
||||
ctx?: ExecutionContext
|
||||
}
|
||||
|
||||
@@ -54,7 +55,7 @@ export type RouterRequest<TExt> = {
|
||||
*
|
||||
* @typedef RouterRequestParams
|
||||
*/
|
||||
export interface RouterRequestParams {
|
||||
export type RouterRequestParams = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -63,7 +64,7 @@ export interface RouterRequestParams {
|
||||
*
|
||||
* @typedef RouterRequestQuery
|
||||
*/
|
||||
export interface RouterRequestQuery {
|
||||
export type RouterRequestQuery = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
@@ -74,7 +75,7 @@ export interface RouterRequestQuery {
|
||||
* @param {RouterContext} ctx
|
||||
* @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
|
||||
}
|
||||
|
||||
@@ -88,7 +89,7 @@ export interface RouterHandler<TEnv = any, TExt = any> {
|
||||
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
|
||||
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
|
||||
*/
|
||||
export interface RouterCorsConfig {
|
||||
export type RouterCorsConfig = {
|
||||
allowOrigin?: string
|
||||
allowMethods?: string
|
||||
allowHeaders?: string
|
||||
@@ -287,11 +288,11 @@ export class Router<TEnv = any, TExt = any> {
|
||||
public cors(config?: RouterCorsConfig): Router<TEnv, TExt> {
|
||||
this.corsEnabled = true
|
||||
this.corsConfig = {
|
||||
allowOrigin: config?.allowOrigin || '*',
|
||||
allowMethods: config?.allowMethods || '*',
|
||||
allowHeaders: config?.allowHeaders || '*',
|
||||
maxAge: config?.maxAge || 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus || 204
|
||||
allowOrigin: config?.allowOrigin ?? '*',
|
||||
allowMethods: config?.allowMethods ?? '*',
|
||||
allowHeaders: config?.allowHeaders ?? '*',
|
||||
maxAge: config?.maxAge ?? 86400,
|
||||
optionsSuccessStatus: config?.optionsSuccessStatus ?? 204
|
||||
}
|
||||
return this
|
||||
}
|
||||
@@ -371,8 +372,8 @@ export class Router<TEnv = any, TExt = any> {
|
||||
/**
|
||||
* Handle requests
|
||||
*
|
||||
* @param {TEnv} env
|
||||
* @param {Request} request
|
||||
* @param {TEnv} env
|
||||
* @param {TExt} [ext]
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
@@ -402,11 +403,12 @@ export class Router<TEnv = any, TExt = any> {
|
||||
}
|
||||
|
||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||
const dbg = this.debugMode
|
||||
|
||||
let response: Response | undefined
|
||||
|
||||
for (const handler of handlers) {
|
||||
const res = await handler({ env, req, ctx })
|
||||
const res = await handler({ env, req, dbg, ctx })
|
||||
|
||||
if (res) {
|
||||
response = res
|
||||
|
||||
Reference in New Issue
Block a user