Compare commits
40 Commits
1b2956b437
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
3b813a0199
|
|||
|
7faffa3dd9
|
|||
|
a08adf3c03
|
|||
|
2e594d09f5
|
|||
|
d1c84cf6f6
|
|||
|
ba67b34a0d
|
|||
|
2d5bdfe40e
|
|||
|
7bb935fa53
|
|||
|
49d5806d89
|
|||
|
73a0d4a4f9
|
|||
|
24a85e9814
|
|||
|
dfdc50ba8a
|
|||
|
67bba2a339
|
|||
|
c21e91bcb6
|
|||
|
fe2f8ec227
|
|||
|
0e78ec4787
|
|||
|
fd7dce7256
|
|||
|
1d72a15ca6
|
|||
|
a740f1b103
|
|||
|
21dc38b676
|
|||
|
9df19a50cd
|
|||
|
7dce99214d
|
|||
|
5aedc0248d
|
|||
|
3aecc4ca5f
|
|||
|
e04bcfb395
|
|||
|
f2ba5f5bc5
|
|||
|
306c046adb
|
|||
|
2dab64be19
|
|||
|
175deddc9c
|
|||
|
ff638ad04f
|
|||
|
b118c28dc7
|
|||
|
9451f466fc
|
|||
|
71fcd6c3c0
|
|||
|
e55392d890
|
|||
|
3aaecd8877
|
|||
|
d8d13c4339
|
|||
|
09d5586cc6
|
|||
|
110bfdd95c
|
|||
|
c68a979614
|
|||
|
a4fd646d6b
|
@@ -11,3 +11,7 @@ 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,8 +1,9 @@
|
|||||||
name: Publish (main)
|
name: Publish
|
||||||
|
run-name: Publish ${{ github.ref_name }}
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
types: [published]
|
types: [ published ]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
@@ -13,19 +14,27 @@ 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 latest --access public
|
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || '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 latest --access public
|
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
|
||||||
31
.github/workflows/release.yml
vendored
Normal file
31
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
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
Normal file
26
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
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
|
||||||
11
.npmignore
11
.npmignore
@@ -1,7 +1,10 @@
|
|||||||
|
.editorconfig
|
||||||
.github/
|
.github/
|
||||||
src/
|
.gitignore
|
||||||
test/
|
|
||||||
.nvmrc
|
.nvmrc
|
||||||
|
coverage/
|
||||||
|
jest.config.ts
|
||||||
MIGRATION.md
|
MIGRATION.md
|
||||||
tsconfig.json
|
src/
|
||||||
.editorconfig
|
tests/
|
||||||
|
tsconfig.json
|
||||||
11
README.md
11
README.md
@@ -4,8 +4,6 @@ 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
|
||||||
|
|
||||||
@@ -20,8 +18,9 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
|
|||||||
- 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
|
||||||
@@ -240,7 +239,6 @@ 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])`
|
||||||
@@ -248,7 +246,6 @@ 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)
|
||||||
@@ -296,7 +293,7 @@ wrangler init <name>
|
|||||||
Use of TypeScript is strongly encouraged :)
|
Use of TypeScript is strongly encouraged :)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i -D @tsndr/cloudflare-worker-router
|
npm i @tsndr/cloudflare-worker-router
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
@@ -410,4 +407,4 @@ export default {
|
|||||||
return router.handle(request, env, ctx)
|
return router.handle(request, env, ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
1540
package-lock.json
generated
1540
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
@@ -1,22 +1,23 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-router",
|
"name": "@tsndr/cloudflare-worker-router",
|
||||||
"version": "3.1.3",
|
"version": "3.3.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"type": "module",
|
||||||
|
"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",
|
||||||
@@ -31,7 +32,9 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^4.20231025.0",
|
"@cloudflare/workers-types": "^4.20250724.0",
|
||||||
"typescript": "^5.2.2"
|
"@edge-runtime/vm": "^5.0.0",
|
||||||
|
"typescript": "^5.8.3",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
71
src/index.ts
71
src/index.ts
@@ -52,6 +52,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,17 +176,6 @@ 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
|
||||||
*
|
*
|
||||||
@@ -263,17 +253,6 @@ 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
|
||||||
*
|
*
|
||||||
@@ -417,7 +396,8 @@ 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(/^(B|b)earer /, '').trim()
|
bearer: () => request.headers.get('Authorization')?.replace(/^[Bb]earer\s/, '').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') {
|
||||||
@@ -428,34 +408,37 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const route = this.getRoute(req)
|
const route = this.getRoute(req)
|
||||||
|
|
||||||
if (!route)
|
|
||||||
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
|
||||||
|
|
||||||
const handlers = [...this.globalHandlers, ...route.handlers]
|
|
||||||
const dbg = this.debugMode
|
|
||||||
|
|
||||||
let response: Response | undefined
|
let response: Response | undefined
|
||||||
|
|
||||||
for (const handler of handlers) {
|
if (!route)
|
||||||
const context = {
|
response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
|
||||||
...(ctxExt ?? {}),
|
|
||||||
env,
|
|
||||||
req,
|
|
||||||
dbg,
|
|
||||||
ctx
|
|
||||||
} as RouterContext<Env, CtxExt, ReqExt>
|
|
||||||
|
|
||||||
const res = await handler(context)
|
if (!response) {
|
||||||
|
const handlers = [
|
||||||
|
...this.globalHandlers,
|
||||||
|
...(route?.handlers ?? [])
|
||||||
|
]
|
||||||
|
|
||||||
if (res) {
|
for (const handler of handlers) {
|
||||||
response = res
|
const context = {
|
||||||
break
|
...(ctxExt ?? {}),
|
||||||
|
env,
|
||||||
|
req,
|
||||||
|
dbg: this.debugMode,
|
||||||
|
ctx
|
||||||
|
} as RouterContext<Env, CtxExt, ReqExt>
|
||||||
|
|
||||||
|
const res = await handler(context)
|
||||||
|
|
||||||
|
if (res) {
|
||||||
|
response = res
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!response)
|
if (!response)
|
||||||
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
|
response = 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)
|
||||||
@@ -464,4 +447,4 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
|
|||||||
|
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
381
tests/index.spec.ts
Normal file
381
tests/index.spec.ts
Normal file
@@ -0,0 +1,381 @@
|
|||||||
|
import { describe, expect, test } from 'vitest'
|
||||||
|
import { Router } from '../src/index'
|
||||||
|
|
||||||
|
describe('Router', () => {
|
||||||
|
test('use', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.use(() => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
router.get('/', () => new Response('failed'))
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('delete', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'DELETE' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.delete('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('get', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'GET' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.get('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('head', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'HEAD' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.head('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('options', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'OPTIONS' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.options('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('patch', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'PATCH' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.patch('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('post', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.post('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.post('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('put', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'PUT' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.put('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.put('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('any', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.any('/test', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
expect(router.any('/', () => testResponse)).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cors', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'GET' })
|
||||||
|
const testOptionsRequest = new Request('https://example.com/', { method: 'OPTIONS' })
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
expect(router.cors()).toBeInstanceOf(Router)
|
||||||
|
|
||||||
|
router.get('/', () => testResponse)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Methods')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Headers')).toBe('*')
|
||||||
|
expect(response.headers.get('Access-Control-Allow-Credentials')).toBe(null)
|
||||||
|
expect(response.headers.get('vary')).toBe(null)
|
||||||
|
expect(response.headers.get('Access-Control-Max-Age')).toBe('86400')
|
||||||
|
|
||||||
|
const optionsRes = await router.handle(testOptionsRequest, {})
|
||||||
|
|
||||||
|
expect(optionsRes.status).toBe(204)
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Origin')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Methods')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Headers')).toBe('*')
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Allow-Credentials')).toBe(null)
|
||||||
|
expect(optionsRes.headers.get('vary')).toBe(null)
|
||||||
|
expect(optionsRes.headers.get('Access-Control-Max-Age')).toBe('86400')
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('params', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/bar/foo')
|
||||||
|
|
||||||
|
router.get('/:foo/:bar', ({ req }) => {
|
||||||
|
return Response.json(req.params)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ foo: 'bar', bar: 'foo' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('query', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/?foo=bar&bar=foo')
|
||||||
|
|
||||||
|
router.get('/', ({ req }) => {
|
||||||
|
return Response.json(req.query)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ foo: 'bar', bar: 'foo' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('404', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('debug mode', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
router.debug()
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('Route not found!')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('handler no response', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/')
|
||||||
|
|
||||||
|
router.debug()
|
||||||
|
|
||||||
|
router.get('/', () => {})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(404)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('Handler did not return a Response!')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('wildcard', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testRequest = new Request('https://example.com/foo/bar')
|
||||||
|
const testResponse = new Response('success', { status: 200 })
|
||||||
|
|
||||||
|
router.get('*', () => testResponse)
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('bearer', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testToken = 'super-secret-token'
|
||||||
|
const testRequest = new Request('https://example.com/', { headers: { 'Authorization': `Bearer ${testToken}` }})
|
||||||
|
|
||||||
|
router.get('/', ({ req }) => new Response(req.bearer()))
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
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', () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testHandlerSuccess = () => new Response('success', { status: 200 })
|
||||||
|
const testHandlerContinue = () => {}
|
||||||
|
const testHandlerFailed = () => new Response('failed', { status: 403 })
|
||||||
|
|
||||||
|
router.get('/success', testHandlerContinue, testHandlerSuccess)
|
||||||
|
router.get('/failed', testHandlerFailed, testHandlerSuccess)
|
||||||
|
|
||||||
|
test('continue', async () => {
|
||||||
|
const testRequest = new Request('https://example.com/success')
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(200)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('block', async () => {
|
||||||
|
const testRequest = new Request('https://example.com/failed')
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(response.status).toEqual(403)
|
||||||
|
|
||||||
|
expect(await response.text()).toBe('failed')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Body', () => {
|
||||||
|
|
||||||
|
test('text then text', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testText = "lorem ipsum dolor sit amet"
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testText })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
text: await req.text(),
|
||||||
|
text2: await req.text()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testText, text2: testText })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('json then json', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
json: await req.json(),
|
||||||
|
json2: await req.json()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ json: testObject, json2: testObject })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('text then json', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
text: await req.text(),
|
||||||
|
json: await req.json()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testJson, json: testObject })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('json then text', async () => {
|
||||||
|
const router = new Router()
|
||||||
|
const testObject = { text: 'cloudflare-worker-router', binary: true, amount: 17 }
|
||||||
|
const testJson = JSON.stringify(testObject)
|
||||||
|
const testRequest = new Request('https://example.com/', { method: 'POST', body: testJson })
|
||||||
|
|
||||||
|
router.post('/', async ({ req }) => {
|
||||||
|
return Response.json({
|
||||||
|
json: await req.json(),
|
||||||
|
text: await req.text()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await router.handle(testRequest, {})
|
||||||
|
|
||||||
|
expect(await response.json()).toMatchObject({ text: testJson, json: testObject })
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": ".",
|
"outDir": ".",
|
||||||
"module": "commonjs",
|
"module": "esnext",
|
||||||
"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"]
|
||||||
}
|
}
|
||||||
9
vite.config.ts
Normal file
9
vite.config.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: 'edge-runtime',
|
||||||
|
reporters: ['verbose'],
|
||||||
|
watch: false
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user