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
Provenance
- Commit
c5cc9f2- Tree
6e67d64- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7efda2e
6 files changed+132 added−106 removed
modified:examples/basic/index.js+10 added
51 unmodified lines52535455565758596061626364656667686941 unmodified lines51 unmodified linesapp.get('/entry/:id', (c) => { const id = c.req.param('id') return c.text(`Your ID is ${id}`)})
// Nested routeconst book = app.route('/book')book.get('/', (c) => c.text('List Books'))book.get('/:id', (c) => { const id = c.req.param('id') return c.text('Get Book: ' + id)})book.post('/', (c) => c.text('Create Book'))
// Redirectapp.get('/redirect', (c) => c.redirect('/'))// Authentication requiredapp.get('/auth/*', (c) => c.text('You are authorized'))41 unmodified linesmodified:src/utils/url.test.ts+21 added-1 removed
11234563 unmodified lines69707172737475767778798081828384858687888990919293import { splitPath, getPattern, getPathFromURL, isAbsoluteURL } from './url'import { splitPath, getPattern, getPathFromURL, isAbsoluteURL, mergePath } from './url'
describe('url', () => { it('splitPath', () => { let ps = splitPath('/')63 unmodified lines expect(isAbsoluteURL('/location')).not.toBeTruthy() expect(isAbsoluteURL('')).not.toBeTruthy() }) })
describe('mergePath', () => { it('mergePath', () => { expect(mergePath('/book', '/')).toBe('/book') expect(mergePath('/book/', '/')).toBe('/book/') expect(mergePath('/book', '/hey')).toBe('/book/hey') expect(mergePath('/book/', '/hey')).toBe('/book/hey') expect(mergePath('/book', '/hey/')).toBe('/book/hey/') expect(mergePath('/book/', '/hey/')).toBe('/book/hey/') expect(mergePath('/book', 'hey', 'say')).toBe('/book/hey/say') expect(mergePath('/book', '/hey/', '/say/')).toBe('/book/hey/say/') expect(mergePath('/book', '/hey/', '/say/', '/')).toBe('/book/hey/say/')
expect(mergePath('book', '/')).toBe('/book') expect(mergePath('book/', '/')).toBe('/book/') expect(mergePath('book', '/hey')).toBe('/book/hey') expect(mergePath('book', 'hey')).toBe('/book/hey') expect(mergePath('book', 'hey/')).toBe('/book/hey/') }) })})modified:src/utils/url.ts+27 added
46 unmodified lines47 return true48 }49 return false50 }51+52+export const mergePath = (...paths: string[]): string => {53+ let p: string = ''54+ let endsWithSlash = false55+56+ for (let path of paths) {57+ /* ['/hey/','/say'] => ['/hey', '/say'] */58+ if (p.endsWith('/')) {59+ p = p.slice(0, -1)60+ endsWithSlash = true61+ }62+63+ /* ['/hey','say'] => ['/hey', '/say'] */64+ if (!path.startsWith('/')) {65+ path = `/${path}`66+ }67+68+ /* ['/hey/', '/'] => `/hey/` */69+ if (path === '/' && endsWithSlash) {70+ p = `${p}/`71+ } else if (path !== '/') {72+ p = `${p}${path}`73+ }74+ }75+76+ return p77+}modified:src/hono.ts+35 added-61 removed
1 import type { Result } from './node'2 import { Node, METHOD_NAME_OF_ALL } from './node'3 import { compose } from './compose'4-import { getPathFromURL } from './utils/url'4+import { getPathFromURL, mergePath } from './utils/url'5 import { Context } from './context'6 import type { Env } from './context'7 8 declare global {53 unmodified lines62 63 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 }69 70 /* 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 }75 77- 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 }80 83- 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 }85 89- 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 }90 95- 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 }95 101- 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 }100 107- 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 }105 113- /*114- We may implement these HTTP methods:115- trace116- copy117- lock118- purge119- unlock120- report121- checkout122- merge123- notify124- subscribe125- unsubscribe126- search127- connect128- */129-130- 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 }111 112 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 }118 119 use(path: string, middleware: MiddlewareHandler): void {120 if (middleware.constructor.name !== 'AsyncFunction') {121 throw new TypeError('middleware must be a async function!')122 }145-123 const router = new Router<MiddlewareHandler>()124 router.add(METHOD_NAME_OF_ALL, path, middleware)125 this.middlewareRouters.push(router)126 }127 128 // 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 }137 138 async matchRoute(method: string, path: string): Promise<Result<Handler[]>> {91 unmodified linesmodified:test/hono.test.ts+27 added-27 removed
121 unmodified lines122 expect(res.status).toBe(200)123 expect(await res.text()).toBe('delete /')124 })125 126- 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'))133+134+ 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'))137+138+ 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')142 137- 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')147 142- 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- })146-147- 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'))152-153- 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')152 158- 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)156+157+ 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')161 163- 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 })168 169 describe('param and query', () => {215 unmodified linesmodified:README.md+12 added-17 removed
37 unmodified lines38 39 40 Now, the named path parameter has types.41 42-42+43 44 ## Install45 46 You can install Hono from npm registry:9 unmodified lines56 ```57 58 ## Methods59 60-Instance of `Hono` has these methods:60+An instance of `Hono` has these methods:61 62 - app.**HTTP_METHOD**(path, handler)63 - app.**all**(path, handler)64 - app.**route**(path)42 unmodified lines107 const title = c.req.param('title')108 ...109 ```110 111-### Chained Route111+### Nested route112 113 ```js114-app115- .route('/api/book')116- .get(() => {...})117- .post(() => {...})118- .put(() => {...})114+const book = app.route('/book')115+book.get('/', (c) => c.text('List Books')) // => GET /book116+book.get('/:id', (c) => {117+ // => GET /book/:id118+ const id = c.req.param('id')119+ return c.text('Get Book: ' + id)120+})121+book.post('/', (c) => c.text('Create Book')) // => POST /book122 ```123 124 ### Custom 404 Response125 39 unmodified lines165 const app = new Hono()166 167 app.use('*', poweredBy())168 app.use('*', logger())166-app.use(167- '/auth/*',168- basicAuth({169- username: 'hono',170- password: 'acoolproject',171- })172-)173-174-...169+app.use('/auth/*', basicAuth({ username: 'hono', password: 'acoolproject' }))170 ```171 172 Available builtin middleware are listed on [src/middleware](https://github.com/yusukebe/hono/tree/master/src/middleware).173 291 unmodified lines