1
0

33 Commits

Author SHA1 Message Date
24a85e9814 3.2.8 2024-09-28 02:29:17 +02:00
dfdc50ba8a update dev dependencies 2024-09-28 02:29:04 +02:00
67bba2a339 3.2.7 2024-09-28 02:25:54 +02:00
c21e91bcb6 npm audit fix 2024-09-28 02:25:46 +02:00
fe2f8ec227 3.2.6 2024-09-28 02:19:32 +02:00
0e78ec4787 return cors headers for 404 response as well 2024-09-28 02:19:07 +02:00
fd7dce7256 3.2.5 2024-09-28 01:53:00 +02:00
1d72a15ca6 update readme 2024-09-28 01:51:05 +02:00
a740f1b103 audit fix 2024-07-15 22:14:32 +02:00
21dc38b676 update keywords 2024-02-24 21:03:35 +01:00
9df19a50cd change to module 2024-02-24 20:59:03 +01:00
7dce99214d switch to vitest 2024-02-24 20:55:23 +01:00
5aedc0248d 3.2.4 2024-01-20 23:39:07 +01:00
3aecc4ca5f update npmignore 2024-01-20 23:38:58 +01:00
e04bcfb395 3.2.3 2024-01-20 23:32:28 +01:00
f2ba5f5bc5 update npmignore 2024-01-20 23:32:17 +01:00
306c046adb update test 2024-01-20 02:49:45 +01:00
2dab64be19 rename job 2024-01-20 02:37:12 +01:00
175deddc9c fix import 2024-01-20 02:36:32 +01:00
ff638ad04f add testing github action 2024-01-20 02:35:06 +01:00
b118c28dc7 3.2.2 2024-01-20 02:28:22 +01:00
9451f466fc move test file to tests directory 2024-01-20 02:27:50 +01:00
71fcd6c3c0 3.2.1 2024-01-20 02:25:07 +01:00
e55392d890 remove connect and trace method 2024-01-20 02:24:38 +01:00
3aaecd8877 3.2.0 2024-01-20 02:22:15 +01:00
d8d13c4339 add npm test command 2024-01-20 02:19:22 +01:00
09d5586cc6 add more tests 2024-01-20 02:15:55 +01:00
110bfdd95c even more tests 2024-01-20 02:15:55 +01:00
c68a979614 working on testing 2024-01-20 02:15:55 +01:00
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
11 changed files with 1782 additions and 107 deletions

View File

@@ -11,3 +11,7 @@ indent_style = tab
[README.md]
indent_style = space
indent_size = 4
[{package,package-lock}.json]
indent_style = space
indent_size = 2

View File

@@ -1,4 +1,4 @@
name: Publish (main)
name: Publish
on:
release:

21
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
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

View File

@@ -1,7 +1,10 @@
.github/
src/
test/
.nvmrc
MIGRATION.md
tsconfig.json
.editorconfig
.github/
.gitignore
.nvmrc
coverage/
jest.config.ts
MIGRATION.md
src/
tests/
tsconfig.json

View File

@@ -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.
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
@@ -240,7 +238,6 @@ Key | Type | Default Value
### Supported Methods
- `router.any(url, [...handlers])`
- `router.connect(url, [...handlers])`
- `router.delete(url, [...handlers])`
- `router.get(url, [...handlers])`
- `router.head(url, [...handlers])`
@@ -248,7 +245,6 @@ Key | Type | Default Value
- `router.patch(url, [...handlers])`
- `router.post(url, [...handlers])`
- `router.put(url, [...handlers])`
- `router.trace(url, [...handlers])`
#### `url` (string)
@@ -296,7 +292,7 @@ wrangler init <name>
Use of TypeScript is strongly encouraged :)
```bash
npm i -D @tsndr/cloudflare-worker-router
npm i @tsndr/cloudflare-worker-router
```

1314
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,23 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.1.2",
"version": "3.2.8",
"description": "",
"main": "index.js",
"type": "module",
"exports": "./index.js",
"types": "index.d.ts",
"scripts": {
"build": "tsc"
"build": "tsc",
"test": "vitest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tsndr/cloudflare-worker-router.git"
},
"keywords": [
"api",
"cloudflare",
"cloudflare-worker",
"cloudflare-workers",
"express",
"expressjs",
"framework",
"middleware",
"router",
@@ -31,7 +32,9 @@
},
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
"devDependencies": {
"@cloudflare/workers-types": "^4.20231025.0",
"typescript": "^5.2.2"
"@cloudflare/workers-types": "^4.20240925.0",
"@edge-runtime/vm": "^4.0.3",
"typescript": "^5.6.2",
"vitest": "^2.1.1"
}
}

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, {
@@ -428,23 +406,25 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
}
const route = this.getRoute(req)
let response: Response | undefined
if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
const handlers = [...this.globalHandlers, ...route.handlers]
const dbg = this.debugMode
let response: Response | undefined
if (!response) {
const handlers = [
...this.globalHandlers,
...(route?.handlers ?? [])
]
for (const handler of handlers) {
const context = {
...(extCtx ?? {}),
...(ctxExt ?? {}),
env,
req,
dbg,
dbg: this.debugMode,
ctx
} as RouterContext<TEnv, TCtx, TReq>
} as RouterContext<Env, CtxExt, ReqExt>
const res = await handler(context)
@@ -453,9 +433,10 @@ export class Router<TEnv = any, TCtx = any, TReq = any> {
break
}
}
}
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) {
response = new Response(response.body, response)

366
tests/index.spec.ts Normal file
View File

@@ -0,0 +1,366 @@
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)
})
})
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 })
})
})

9
vite.config.ts Normal file
View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'edge-runtime',
reporters: ['verbose'],
watch: false
}
})