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
Provenance
- Commit
04460a6- Tree
a46d37a- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
6b7a96f
4 files changed+111 added−39 removed
modified:src/context.ts+1 added-1 removed
24 unmodified lines25262728292930313233105 unmodified linesExpand all24 unmodified lines constructor( req: Request<RequestParamKeyType>, opts?: { res: Response; env: Env; event: FetchEvent } ) { this.req = this.initRequest(req) this.req = this.initRequest<RequestParamKeyType>(req) Object.assign(this, opts) this.#headers = {} }
105 unmodified linesExpand allmodified:src/hono.test.ts+48 added-1 removed
1-import type { Context } from '@/context'1 import { Hono } from '@/hono'2+import { poweredBy } from '@/middleware/powered-by'3 4 describe('GET Request', () => {5 const app = new Hono()6 136 unmodified lines143 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 })147+148+ 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 })174 175 describe('param and query', () => {176 const app = new Hono()82 unmodified lines259 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 })263+264+ 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 })285 286 describe('Not Found', () => {287 const app = new Hono()106 unmodified linesmodified:src/hono.ts+44 added-37 removed
13 unmodified lines14 }15 }16 17 export type Handler<RequestParamKeyType = string> = (18- c: Context<RequestParamKeyType | string>,18+ c: Context<RequestParamKeyType>,19 next?: Next20 ) => Response | Promise<Response>21 export type MiddlewareHandler = (c: Context, next: Next) => Promise<void>22 export type NotFoundHandler = (c: Context) => Response | Promise<Response>12 unmodified lines35 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`36 ? ParamKey<Component> | ParamKeys<Rest>37 : ParamKey<Path>38 39-function 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: T39+interface 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+}43+44+const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch', 'all'] as const45+type Methods = typeof methods[number]46+47+function 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 }54 55-export class Hono extends defineDynamicClass(56- 'get',57- 'post',58- 'put',59- 'delete',60- 'head',61- 'options',62- 'patch',63- 'all'64-) {55+export 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: string62 71- constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {63+ constructor(init: Partial<Pick<Hono<P>, 'routerClass' | 'strict'>> = {}) {64 super()73-74- 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 })77 78 Object.assign(this, init)13 unmodified lines92 const message = 'Internal Server Error'93 return c.text(message, 500)94 }95 98- 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 }102 105- 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 }121 114- onError(handler: ErrorHandler): Hono {122+ onError(handler: ErrorHandler): Hono<P> {123 this.errorHandler = handler124 return this125 }126 119- notFound(handler: NotFoundHandler): Hono {127+ notFound(handler: NotFoundHandler): Hono<P> {128 this.notFoundHandler = handler129 return this130 }131 124- // 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 linesmodified:README.md+18 added
125 unmodified lines126 ...127 })128 ```129 130+### Chained route131+132+```js133+app134+ .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+```144+145 ### Nested route146 147 ```js148 const book = app.route('/book')40 unmodified lines189 const app = new Hono()190 191 app.use('*', poweredBy())192 app.use('*', logger())193+// Or you can write:194+// app.use('*', poweredBy()).use(logger())195+196 app.use(197 '/auth/*',198 basicAuth({199 username: 'hono',353 unmodified lines