Skip to content
Myr

feat: nested route (#105)

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

# BREAKING CHANGES!!! `app.route` is changed: **Chained route** is obsolete: ``` app.route('/') .get((c) => c.text('get /')) // ^^^ Not working now!! ``` Now, `app.route` enables **nested route**: ``` const book = app.route('/book') book.get('/', (c) => c.text('List books')) // => GET /book book.get('/:id', (c) => { return c.text('Get Book: ' + c.req.param('id'))) // => GET /book/:id }) ```

authored by Yusuke Wada · committed by GitHub · parent 7efda2e · Browse files · 6 files+132 added−106 removed
This commit

State

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

Diff stats

6 files+132 added−106 removed

  • tests:+48 added−28 removed
  • other:+84 added−78 removed

6 files+132 added−106 removed

modified:examples/basic/index.js+10 added
modified:src/utils/url.test.ts+21 added-1 removed
modified:src/utils/url.ts+27 added
46 unmodified lines
47 return true48 }49 return false50}5152export const mergePath = (...paths: string[]): string => {53 let p: string = ''54 let endsWithSlash = false5556 for (let path of paths) {57 /* ['/hey/','/say'] => ['/hey', '/say'] */58 if (p.endsWith('/')) {59 p = p.slice(0, -1)60 endsWithSlash = true61 }6263 /* ['/hey','say'] => ['/hey', '/say'] */64 if (!path.startsWith('/')) {65 path = `/${path}`66 }6768 /* ['/hey/', '/'] => `/hey/` */69 if (path === '/' && endsWithSlash) {70 p = `${p}/`71 } else if (path !== '/') {72 p = `${p}${path}`73 }74 }7576 return p77}
modified:src/hono.ts+35 added-61 removed
1import type { Result } from './node'2import { Node, METHOD_NAME_OF_ALL } from './node'3import { compose } from './compose'4import { getPathFromURL } from './utils/url'4import { getPathFromURL, mergePath } from './utils/url'5import { Context } from './context'6import type { Env } from './context'78declare global {
53 unmodified lines
6263 constructor(init: Init = { strict: true }) {64 this.router = new Router()65 this.middlewareRouters = []66 this.tempPath = '/'66 this.tempPath = null67 this.strict = init.strict // strict routing - default is true68 }6970 /* HTTP METHODS */71 get<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono72 get(arg: Handler<never>, ...args: Handler<never>[]): Hono73 get(arg: string | Handler, ...args: Handler[]): Hono {74 return this.addRoute('get', arg, ...args)71 get<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono72 get(path: string, ...args: Handler[]): Hono {73 return this.addRoute('get', path, ...args)74 }7577 post<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono78 post(arg: Handler, ...args: Handler[]): Hono79 post(arg: string | Handler, ...args: Handler[]): Hono {80 return this.addRoute('post', arg, ...args)76 post<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono77 post(path: string, ...args: Handler[]): Hono {78 return this.addRoute('post', path, ...args)79 }8083 put<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono84 put(arg: Handler, ...args: Handler[]): Hono85 put(arg: string | Handler, ...args: Handler[]): Hono {86 return this.addRoute('put', arg, ...args)81 put<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono82 put(path: string, ...args: Handler[]): Hono {83 return this.addRoute('put', path, ...args)84 }8589 head<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono90 head(arg: Handler, ...args: Handler[]): Hono91 head(arg: string | Handler, ...args: Handler[]): Hono {92 return this.addRoute('head', arg, ...args)86 head<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono87 head(path: string, ...args: Handler[]): Hono {88 return this.addRoute('head', path, ...args)89 }9095 delete<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono96 delete(arg: Handler, ...args: Handler[]): Hono97 delete(arg: string | Handler, ...args: Handler[]): Hono {98 return this.addRoute('delete', arg, ...args)91 delete<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono92 delete(path: string, ...args: Handler[]): Hono {93 return this.addRoute('delete', path, ...args)94 }95101 options<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono102 options(arg: Handler, ...args: Handler[]): Hono103 options(arg: string | Handler, ...args: Handler[]): Hono {104 return this.addRoute('options', arg, ...args)96 options<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono97 options(path: string, ...args: Handler[]): Hono {98 return this.addRoute('options', path, ...args)99 }100107 patch<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono108 patch(arg: Handler, ...args: Handler[]): Hono109 patch(arg: string | Handler, ...args: Handler[]): Hono {110 return this.addRoute('patch', arg, ...args)101 patch<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono102 patch(path: string, ...args: Handler[]): Hono {103 return this.addRoute('patch', path, ...args)104 }105113 /*114 We may implement these HTTP methods:115 trace116 copy117 lock118 purge119 unlock120 report121 checkout122 merge123 notify124 subscribe125 unsubscribe126 search127 connect128 */129130 all<Path extends string>(arg: Path, ...args: Handler<ParamKeys<Path>>[]): Hono131 all(arg: Handler<never>, ...args: Handler<never>[]): Hono132 all(arg: string | Handler, ...args: Handler[]): Hono {133 return this.addRoute('all', arg, ...args)106 /* Any methods */107 all<Path extends string>(path: Path, ...args: Handler<ParamKeys<Path>>[]): Hono108 all(path: string, ...args: Handler[]): Hono {109 return this.addRoute('all', path, ...args)110 }111112 route(path: string): Hono {137 this.tempPath = path138 return this113 const newHono: Hono = new Hono()114 newHono.tempPath = path115 newHono.router = this.router116 return newHono117 }118119 use(path: string, middleware: MiddlewareHandler): void {120 if (middleware.constructor.name !== 'AsyncFunction') {121 throw new TypeError('middleware must be a async function!')122 }145123 const router = new Router<MiddlewareHandler>()124 router.add(METHOD_NAME_OF_ALL, path, middleware)125 this.middlewareRouters.push(router)126 }127128 // addRoute('get', '/', handler)152 addRoute(method: string, arg: string | Handler, ...args: Handler[]): Hono {129 addRoute(method: string, path: string, ...args: Handler[]): Hono {130 method = method.toUpperCase()154 if (typeof arg === 'string') {155 this.tempPath = arg156 this.router.add(method, arg, args)157 } else {158 args.unshift(arg)159 this.router.add(method, this.tempPath, args)131 if (this.tempPath) {132 path = mergePath(this.tempPath, path)133 }134 this.router.add(method, path, args)135 return this136 }137138 async matchRoute(method: string, path: string): Promise<Result<Handler[]>> {
91 unmodified lines
modified:test/hono.test.ts+27 added-27 removed
121 unmodified lines
122 expect(res.status).toBe(200)123 expect(await res.text()).toBe('delete /')124 })125126 it('Chained route', async () => {127 app128 .route('/route')129 .get(() => new Response('get /route'))130 .post(() => new Response('post /route'))131 .put(() => new Response('put /route'))132 let req = new Request('http://localhost/route', { method: 'GET' })126 it('Nested route', async () => {127 const book = app.route('/book')128 book.get('/', (c) => c.text('get /book'))129 book.get('/:id', (c) => {130 return c.text('get /book/' + c.req.param('id'))131 })132 book.post('/', (c) => c.text('post /book'))133134 const user = app.route('/user')135 user.get('/login', (c) => c.text('get /user/login'))136 user.post('/regist', (c) => c.text('post /user/regist'))137138 let req = new Request('http://localhost/book', { method: 'GET' })139 let res = await app.dispatch(req)140 expect(res.status).toBe(200)135 expect(await res.text()).toBe('get /route')141 expect(await res.text()).toBe('get /book')142137 req = new Request('http://localhost/route', { method: 'POST' })143 req = new Request('http://localhost/book/123', { method: 'GET' })144 res = await app.dispatch(req)145 expect(res.status).toBe(200)140 expect(await res.text()).toBe('post /route')146 expect(await res.text()).toBe('get /book/123')147142 req = new Request('http://localhost/route', { method: 'DELETE' })148 req = new Request('http://localhost/book', { method: 'POST' })149 res = await app.dispatch(req)144 expect(res.status).toBe(404)145 })146147 it('Chained route without route method', async () => {148 app149 .get('/without-route', () => new Response('get /without-route'))150 .post(() => new Response('post /without-route'))151 .put(() => new Response('put /without-route'))152153 let req = new Request('http://localhost/without-route', { method: 'GET' })154 let res = await app.dispatch(req)150 expect(res.status).toBe(200)156 expect(await res.text()).toBe('get /without-route')151 expect(await res.text()).toBe('post /book')152158 req = new Request('http://localhost/without-route', { method: 'POST' })153 req = new Request('http://localhost/book/', { method: 'GET' })154 res = await app.dispatch(req)155 expect(res.status).toBe(404)156157 req = new Request('http://localhost/user/login', { method: 'GET' })158 res = await app.dispatch(req)159 expect(res.status).toBe(200)161 expect(await res.text()).toBe('post /without-route')160 expect(await res.text()).toBe('get /user/login')161163 req = new Request('http://localhost/without-route', { method: 'DELETE' })162 req = new Request('http://localhost/user/regist', { method: 'POST' })163 res = await app.dispatch(req)165 expect(res.status).toBe(404)164 expect(res.status).toBe(200)165 expect(await res.text()).toBe('post /user/regist')166 })167})168169describe('param and query', () => {
215 unmodified lines
modified:README.md+12 added-17 removed
37 unmodified lines
38![Demo](https://user-images.githubusercontent.com/10682/151973526-342644f9-71c5-4fee-81f4-64a7558bb192.gif)3940Now, the named path parameter has types.4142![Demo](https://user-images.githubusercontent.com/10682/154018316-50456d41-eefd-4ec9-b444-2d6f22def99d.png)42![Demo](https://user-images.githubusercontent.com/10682/154179671-9e491597-6778-44ac-a8e6-4483d7ad5393.png)4344## Install4546You can install Hono from npm registry:
9 unmodified lines
56```5758## Methods5960Instance of `Hono` has these methods:60An instance of `Hono` has these methods:6162- app.**HTTP_METHOD**(path, handler)63- app.**all**(path, handler)64- app.**route**(path)
42 unmodified lines
107 const title = c.req.param('title')108 ...109```110111### Chained Route111### Nested route112113```js114app115 .route('/api/book')116 .get(() => {...})117 .post(() => {...})118 .put(() => {...})114const book = app.route('/book')115book.get('/', (c) => c.text('List Books')) // => GET /book116book.get('/:id', (c) => {117 // => GET /book/:id118 const id = c.req.param('id')119 return c.text('Get Book: ' + id)120})121book.post('/', (c) => c.text('Create Book')) // => POST /book122```123124### Custom 404 Response125
39 unmodified lines
165const app = new Hono()166167app.use('*', poweredBy())168app.use('*', logger())166app.use(167 '/auth/*',168 basicAuth({169 username: 'hono',170 password: 'acoolproject',171 })172)173174...169app.use('/auth/*', basicAuth({ username: 'hono', password: 'acoolproject' }))170```171172Available builtin middleware are listed on [src/middleware](https://github.com/yusukebe/hono/tree/master/src/middleware).173
291 unmodified lines