Compare commits
3 Commits
v3.3.0
...
1b2956b437
| Author | SHA1 | Date | |
|---|---|---|---|
|
1b2956b437
|
|||
|
64458ca755
|
|||
|
eeea1102af
|
@@ -11,7 +11,3 @@ indent_style = tab
|
|||||||
[README.md]
|
[README.md]
|
||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
[{package,package-lock}.json]
|
|
||||||
indent_style = space
|
|
||||||
indent_size = 2
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
name: Publish
|
name: Publish (main)
|
||||||
run-name: Publish ${{ github.ref_name }}
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
types: [ published ]
|
types: [published]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
@@ -14,27 +13,19 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: latest
|
node-version: latest
|
||||||
registry-url: https://registry.npmjs.org/
|
registry-url: https://registry.npmjs.org/
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: npm test
|
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
|
||||||
- name: Publish to npmjs
|
- name: Publish to npmjs
|
||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||||
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
|
run: npm publish --tag latest --access public
|
||||||
|
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: latest
|
node-version: latest
|
||||||
registry-url: https://npm.pkg.github.com/
|
registry-url: https://npm.pkg.github.com/
|
||||||
|
|
||||||
- name: Publish to GPR
|
- name: Publish to GPR
|
||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||||
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
|
run: npm publish --tag latest --access public
|
||||||
31
.github/workflows/release.yml
vendored
31
.github/workflows/release.yml
vendored
@@ -1,31 +0,0 @@
|
|||||||
name: Release
|
|
||||||
run-name: Release ${{ github.ref_name }}
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- 'v*'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- uses: actions/setup-node@v3
|
|
||||||
with:
|
|
||||||
node-version: latest
|
|
||||||
registry-url: https://registry.npmjs.org/
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: npm test
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: npm run build
|
|
||||||
|
|
||||||
- name: Create release
|
|
||||||
run: gh release create ${{ github.ref_name }} --draft --generate-notes ${{ contains(github.ref_name, '-') && '--prerelease --latest=false' || '--latest' }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
26
.github/workflows/test.yml
vendored
26
.github/workflows/test.yml
vendored
@@ -1,26 +0,0 @@
|
|||||||
name: Test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ main ]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
run:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- uses: actions/setup-node@v3
|
|
||||||
with:
|
|
||||||
node-version: latest
|
|
||||||
registry-url: https://registry.npmjs.org/
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: npm test
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: npm run build
|
|
||||||
13
.npmignore
13
.npmignore
@@ -1,10 +1,7 @@
|
|||||||
.editorconfig
|
|
||||||
.github/
|
.github/
|
||||||
.gitignore
|
|
||||||
.nvmrc
|
|
||||||
coverage/
|
|
||||||
jest.config.ts
|
|
||||||
MIGRATION.md
|
|
||||||
src/
|
src/
|
||||||
tests/
|
test/
|
||||||
tsconfig.json
|
.nvmrc
|
||||||
|
MIGRATION.md
|
||||||
|
tsconfig.json
|
||||||
|
.editorconfig
|
||||||
11
README.md
11
README.md
@@ -4,6 +4,8 @@ Cloudflare Workers Router is a super lightweight router (1.0K gzipped) with midd
|
|||||||
|
|
||||||
When I was trying out Cloudflare Workers I almost immediately noticed how fast it was compared to other serverless offerings. So I wanted to build a full-fledged API to see how it performs doing real work, but since I wasn't able to find a router that suited my needs I created my own.
|
When I was trying out Cloudflare Workers I almost immediately noticed how fast it was compared to other serverless offerings. So I wanted to build a full-fledged API to see how it performs doing real work, but since I wasn't able to find a router that suited my needs I created my own.
|
||||||
|
|
||||||
|
I worked a lot with [Express.js](https://expressjs.com/) in the past and really enjoyed their middleware approach, but since none of the available Cloudflare Worker routers offered middleware support at the time, I felt the need to create this router.
|
||||||
|
|
||||||
|
|
||||||
## Contents
|
## Contents
|
||||||
|
|
||||||
@@ -18,9 +20,8 @@ When I was trying out Cloudflare Workers I almost immediately noticed how fast i
|
|||||||
- ZERO dependencies
|
- ZERO dependencies
|
||||||
- Lightweight (1.0K gzipped)
|
- Lightweight (1.0K gzipped)
|
||||||
- Fully written in TypeScript
|
- Fully written in TypeScript
|
||||||
|
- Integrated Debug-Mode & CORS helper
|
||||||
- Built specifically around Middlewares
|
- Built specifically around Middlewares
|
||||||
- Debug-Mode, CORS and Bearer helpers
|
|
||||||
- Allows accessing request body multiple times
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
@@ -239,6 +240,7 @@ Key | Type | Default Value
|
|||||||
### Supported Methods
|
### Supported Methods
|
||||||
|
|
||||||
- `router.any(url, [...handlers])`
|
- `router.any(url, [...handlers])`
|
||||||
|
- `router.connect(url, [...handlers])`
|
||||||
- `router.delete(url, [...handlers])`
|
- `router.delete(url, [...handlers])`
|
||||||
- `router.get(url, [...handlers])`
|
- `router.get(url, [...handlers])`
|
||||||
- `router.head(url, [...handlers])`
|
- `router.head(url, [...handlers])`
|
||||||
@@ -246,6 +248,7 @@ Key | Type | Default Value
|
|||||||
- `router.patch(url, [...handlers])`
|
- `router.patch(url, [...handlers])`
|
||||||
- `router.post(url, [...handlers])`
|
- `router.post(url, [...handlers])`
|
||||||
- `router.put(url, [...handlers])`
|
- `router.put(url, [...handlers])`
|
||||||
|
- `router.trace(url, [...handlers])`
|
||||||
|
|
||||||
|
|
||||||
#### `url` (string)
|
#### `url` (string)
|
||||||
@@ -293,7 +296,7 @@ wrangler init <name>
|
|||||||
Use of TypeScript is strongly encouraged :)
|
Use of TypeScript is strongly encouraged :)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i @tsndr/cloudflare-worker-router
|
npm i -D @tsndr/cloudflare-worker-router
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
@@ -407,4 +410,4 @@ export default {
|
|||||||
return router.handle(request, env, ctx)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
9
jest.config.ts
Normal file
9
jest.config.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { Config } from 'jest'
|
||||||
|
|
||||||
|
const config: Config = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
verbose: true
|
||||||
|
}
|
||||||
|
|
||||||
|
export default config
|
||||||
4848
package-lock.json
generated
4848
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
@@ -1,23 +1,22 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "3.3.0",
|
"version": "3.1.3",
|
||||||
"description": "",
|
"description": "",
|
||||||
"type": "module",
|
"main": "index.js",
|
||||||
"exports": "./index.js",
|
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc"
|
||||||
"test": "vitest"
|
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/tsndr/cloudflare-worker-router.git"
|
"url": "git+https://github.com/tsndr/cloudflare-worker-router.git"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"api",
|
|
||||||
"cloudflare",
|
"cloudflare",
|
||||||
"cloudflare-worker",
|
"cloudflare-worker",
|
||||||
"cloudflare-workers",
|
"cloudflare-workers",
|
||||||
|
"express",
|
||||||
|
"expressjs",
|
||||||
"framework",
|
"framework",
|
||||||
"middleware",
|
"middleware",
|
||||||
"router",
|
"router",
|
||||||
@@ -32,9 +31,12 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^4.20241022.0",
|
"@cloudflare/workers-types": "^4.20231025.0",
|
||||||
"@edge-runtime/vm": "^4.0.3",
|
"@jest/globals": "^29.7.0",
|
||||||
"typescript": "^5.6.3",
|
"@types/jest": "^29.5.11",
|
||||||
"vitest": "^2.1.3"
|
"jest": "^29.7.0",
|
||||||
|
"ts-jest": "^29.1.1",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"typescript": "^5.2.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, test } from 'vitest'
|
import { describe, expect, test } from '@jest/globals'
|
||||||
import { Router } from '../src/index'
|
import { Router } from '.'
|
||||||
|
|
||||||
describe('Router', () => {
|
describe('Router', () => {
|
||||||
test('use', async () => {
|
test('use', async () => {
|
||||||
@@ -261,21 +261,6 @@ describe('Router', () => {
|
|||||||
|
|
||||||
expect(await response.text()).toBe(testToken)
|
expect(await response.text()).toBe(testToken)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('basic', async () => {
|
|
||||||
const router = new Router()
|
|
||||||
const testCredentials = ['user', 'password']
|
|
||||||
const testBasicAuth = btoa(testCredentials.join(':'))
|
|
||||||
const testRequest = new Request('https://example.com/', { headers: { 'Authorization': `Basic ${testBasicAuth}` }})
|
|
||||||
|
|
||||||
router.get('/', ({ req }) => Response.json(req.basic()))
|
|
||||||
|
|
||||||
const response = await router.handle(testRequest, {})
|
|
||||||
|
|
||||||
expect(response.status).toEqual(200)
|
|
||||||
|
|
||||||
expect(await response.json()).toMatchObject(testCredentials)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('Middleware', () => {
|
describe('Middleware', () => {
|
||||||
65
src/index.ts
65
src/index.ts
@@ -52,7 +52,6 @@ export type RouterRequest<ReqExt> = ReqExt & {
|
|||||||
formData(): Promise<FormData>
|
formData(): Promise<FormData>
|
||||||
blob(): Promise<Blob>
|
blob(): Promise<Blob>
|
||||||
bearer(): string | undefined
|
bearer(): string | undefined
|
||||||
basic(): [string, string]
|
|
||||||
cf?: IncomingRequestCfProperties
|
cf?: IncomingRequestCfProperties
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,6 +175,17 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register CONNECT route
|
||||||
|
*
|
||||||
|
* @param {string} url
|
||||||
|
* @param {RouterHandler[]} handlers
|
||||||
|
* @returns {Router}
|
||||||
|
*/
|
||||||
|
public connect(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
|
return this.register('CONNECT', url, handlers)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register DELETE route
|
* Register DELETE route
|
||||||
*
|
*
|
||||||
@@ -253,6 +263,17 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
return this.register('PUT', url, handlers)
|
return this.register('PUT', url, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register TRACE route
|
||||||
|
*
|
||||||
|
* @param {string} url
|
||||||
|
* @param {RouterHandler[]} handlers
|
||||||
|
* @returns {Router}
|
||||||
|
*/
|
||||||
|
public trace(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
|
||||||
|
return this.register('TRACE', url, handlers)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register route, ignoring method
|
* Register route, ignoring method
|
||||||
*
|
*
|
||||||
@@ -396,8 +417,7 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
|
json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
|
||||||
formData: async (): Promise<FormData> => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(),
|
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(),
|
blob: async (): Promise<Blob> => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(),
|
||||||
bearer: () => request.headers.get('Authorization')?.replace(/^[Bb]earer\s/, '').trim(),
|
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
|
||||||
basic: () => (atob(request.headers.get('Authorization')?.replace(/^[Bb]asic\s/, '').trim() ?? '') || undefined)?.split(':')
|
|
||||||
} as RouterRequest<ReqExt>
|
} as RouterRequest<ReqExt>
|
||||||
|
|
||||||
if (this.corsEnabled && req.method === 'OPTIONS') {
|
if (this.corsEnabled && req.method === 'OPTIONS') {
|
||||||
@@ -408,37 +428,34 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const route = this.getRoute(req)
|
const route = this.getRoute(req)
|
||||||
let response: Response | undefined
|
|
||||||
|
|
||||||
if (!route)
|
if (!route)
|
||||||
response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||||
|
|
||||||
if (!response) {
|
const handlers = [...this.globalHandlers, ...route.handlers]
|
||||||
const handlers = [
|
const dbg = this.debugMode
|
||||||
...this.globalHandlers,
|
|
||||||
...(route?.handlers ?? [])
|
|
||||||
]
|
|
||||||
|
|
||||||
for (const handler of handlers) {
|
let response: Response | undefined
|
||||||
const context = {
|
|
||||||
...(ctxExt ?? {}),
|
|
||||||
env,
|
|
||||||
req,
|
|
||||||
dbg: this.debugMode,
|
|
||||||
ctx
|
|
||||||
} as RouterContext<Env, CtxExt, ReqExt>
|
|
||||||
|
|
||||||
const res = await handler(context)
|
for (const handler of handlers) {
|
||||||
|
const context = {
|
||||||
|
...(ctxExt ?? {}),
|
||||||
|
env,
|
||||||
|
req,
|
||||||
|
dbg,
|
||||||
|
ctx
|
||||||
|
} as RouterContext<Env, CtxExt, ReqExt>
|
||||||
|
|
||||||
if (res) {
|
const res = await handler(context)
|
||||||
response = res
|
|
||||||
break
|
if (res) {
|
||||||
}
|
response = res
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!response)
|
if (!response)
|
||||||
response = new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
||||||
|
|
||||||
if (this.corsEnabled) {
|
if (this.corsEnabled) {
|
||||||
response = new Response(response.body, response)
|
response = new Response(response.body, response)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": ".",
|
"outDir": ".",
|
||||||
"module": "esnext",
|
"module": "commonjs",
|
||||||
"target": "esnext",
|
"target": "esnext",
|
||||||
"lib": ["esnext"],
|
"lib": ["esnext"],
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
@@ -23,4 +23,4 @@
|
|||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { defineConfig } from 'vitest/config'
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
environment: 'edge-runtime',
|
|
||||||
reporters: ['verbose'],
|
|
||||||
watch: false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
Reference in New Issue
Block a user