Skip to content
Myr

feat: chained routing (#173)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat: enable chained routing * write tests * initialize `#tempPath` * Update readme

authored by Yusuke Wada · committed by GitHub · parent 6b7a96f · Browse files · 4 files+111 added−39 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+111 added−39 removed

  • tests:+48 added−1 removed
  • other:+63 added−38 removed

4 files+111 added−39 removed

modified:src/context.ts+1 added-1 removed
modified:src/hono.test.ts+48 added-1 removed
1import type { Context } from '@/context'1import { Hono } from '@/hono'2import { poweredBy } from '@/middleware/powered-by'34describe('GET Request', () => {5 const app = new Hono()6
136 unmodified lines
143 res = await app.request('http://localhost/user/register', { method: 'POST' })144 expect(res.status).toBe(200)145 expect(await res.text()).toBe('post /user/register')146 })147148 describe('Chained route', () => {149 app150 .get('/chained/:abc', (c) => {151 const abc = c.req.param('abc')152 return c.text(`GET for ${abc}`)153 })154 .post((c) => {155 const abc = c.req.param('abc')156 return c.text(`POST for ${abc}`)157 })158 it('Should return 200 response from GET request', async () => {159 const res = await app.request('http://localhost/chained/abc', { method: 'GET' })160 expect(res.status).toBe(200)161 expect(await res.text()).toBe('GET for abc')162 })163 it('Should return 200 response from POST request', async () => {164 const res = await app.request('http://localhost/chained/abc', { method: 'POST' })165 expect(res.status).toBe(200)166 expect(await res.text()).toBe('POST for abc')167 })168 it('Should return 404 response from PUT request', async () => {169 const res = await app.request('http://localhost/chained/abc', { method: 'PUT' })170 expect(res.status).toBe(404)171 })172 })173})174175describe('param and query', () => {176 const app = new Hono()
82 unmodified lines
259 expect(await res.text()).toBe('message')260 expect(res.headers.get('x-custom')).toBe('root')261 expect(res.headers.get('x-message-2')).toBe('custom-header-2')262 })263264 describe.only('Chained route', () => {265 app266 .use('/chained/*', async (c, next) => {267 c.req.headers.append('x-before', 'abc')268 await next()269 })270 .use(async (c, next) => {271 await next()272 c.header('x-after', c.req.header('x-before'))273 })274 .get('/chained/abc', (c) => {275 return c.text('GET chained')276 })277 })278 it('Should return 200 response with chained route', async () => {279 const res = await app.request('http://localhost/chained/abc')280 expect(res.status).toBe(200)281 expect(await res.text()).toBe('GET chained')282 expect(res.headers.get('x-after')).toBe('abc')283 })284})285286describe('Not Found', () => {287 const app = new Hono()
106 unmodified lines
modified:src/hono.ts+44 added-37 removed
13 unmodified lines
14 }15}1617export type Handler<RequestParamKeyType = string> = (18 c: Context<RequestParamKeyType | string>,18 c: Context<RequestParamKeyType>,19 next?: Next20) => Response | Promise<Response>21export type MiddlewareHandler = (c: Context, next: Next) => Promise<void>22export type NotFoundHandler = (c: Context) => Response | Promise<Response>
12 unmodified lines
35type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`36 ? ParamKey<Component> | ParamKeys<Rest>37 : ParamKey<Path>3839function defineDynamicClass<T extends string[]>(40 ...methods: T41): {42 new (): {43 [K in T[number]]: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono44 } & {45 methods: T39interface HandlerInterface<T extends string> {40 <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>): Hono<Path>41 <Path extends T>(handler: Handler<ParamKeys<T>>): Hono<Path>42}4344const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch', 'all'] as const45type Methods = typeof methods[number]4647function defineDynamicClass(): {48 new <T extends string>(): {49 [K in Methods]: HandlerInterface<T>50 }51} {48 return class {49 get methods() {50 return methods51 }52 } as any52 return class {} as any53}5455export class Hono extends defineDynamicClass(56 'get',57 'post',58 'put',59 'delete',60 'head',61 'options',62 'patch',63 'all'64) {55export class Hono<P extends string> extends defineDynamicClass()<P> {56 readonly routerClass: { new (): Router<any> } = TrieRouter57 readonly strict: boolean = true // strict routing - default is true58 #router: Router<Handler>59 #middlewareRouters: Router<MiddlewareHandler>[]60 #tempPath: string61 private path: string6271 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {63 constructor(init: Partial<Pick<Hono<P>, 'routerClass' | 'strict'>> = {}) {64 super()7374 this.methods.map((method) => {75 this[method] = <Path extends string>(path: Path, handler: Handler) => {76 return this.addRoute(method, path, handler)65 methods.map((method) => {66 this[method] = <Path extends string>(67 arg1: Path | Handler<ParamKeys<P>>,68 arg2?: Handler<ParamKeys<Path>>69 ) => {70 if (typeof arg1 === 'string') {71 this.path = arg172 return this.addRoute(method, this.path, arg2)73 }74 return this.addRoute(method, this.path, arg1)75 }76 })7778 Object.assign(this, init)
13 unmodified lines
92 const message = 'Internal Server Error'93 return c.text(message, 500)94 }9598 route(path: string): Hono {99 const newHono: Hono = new Hono()96 route(path: string): Hono<P> {97 const newHono: Hono<P> = new Hono()98 newHono.#tempPath = path99 newHono.#router = this.#router100 return newHono101 }102105 use(path: string, middleware: MiddlewareHandler): void {106 if (middleware.constructor.name !== 'AsyncFunction') {103 use(path: string, middleware: MiddlewareHandler): Hono<P>104 use(middleware: MiddlewareHandler): Hono<P>105 use(arg1: string | MiddlewareHandler, arg2?: MiddlewareHandler): Hono<P> {106 let handler: MiddlewareHandler107 if (typeof arg1 === 'string') {108 this.path = arg1109 handler = arg2110 } else {111 handler = arg1112 }113 if (handler.constructor.name !== 'AsyncFunction') {114 throw new TypeError('middleware must be a async function!')115 }116 const router = new this.routerClass()110 router.add(METHOD_NAME_OF_ALL, path, middleware)117 router.add(METHOD_NAME_OF_ALL, this.path, handler)118 this.#middlewareRouters.push(router)119 return this120 }121114 onError(handler: ErrorHandler): Hono {122 onError(handler: ErrorHandler): Hono<P> {123 this.errorHandler = handler124 return this125 }126119 notFound(handler: NotFoundHandler): Hono {127 notFound(handler: NotFoundHandler): Hono<P> {128 this.notFoundHandler = handler129 return this130 }131124 // addRoute('get', '/', handler)125 private addRoute(method: string, path: string, handler: Handler): Hono {132 private addRoute(method: string, path: string, handler: Handler): Hono<P> {133 method = method.toUpperCase()134 if (this.#tempPath) {135 path = mergePath(this.#tempPath, path)136 }
67 unmodified lines
modified:README.md+18 added
125 unmodified lines
126 ...127})128```129130### Chained route131132```js133app134 .get('/endpoint', (c) => {135 return c.text('GET /endpoint')136 })137 .post((c) => {138 return c.text('POST /endpoint')139 })140 .delete((c) => {141 return c.text('DELETE /endpoint')142 })143```144145### Nested route146147```js148const book = app.route('/book')
40 unmodified lines
189const app = new Hono()190191app.use('*', poweredBy())192app.use('*', logger())193// Or you can write:194// app.use('*', poweredBy()).use(logger())195196app.use(197 '/auth/*',198 basicAuth({199 username: 'hono',
353 unmodified lines