feat(app): introduce `app.on(method, path, handler)` (#653)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(app): introduce `app.on(method, path, handler)` * Refactoring of feat/on branche (#655) * refactor(reg-exp-router): Use `includes` instead of `find` to check if an element is in an array. * fix(static-router): Copy middleware from METHOD_NAME_ALL for new method. * chore: denoify
authored by Yusuke Wada · committed by GitHub · parent 15a5119 · Browse files · 11 files·+128 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
11 files+128 added−12 removed
- tests:+72 added−8 removed
- other:+56 added−4 removed
Provenance
- Commit
b963d6e- Tree
3883942- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
15a5119
11 files changed+128 added−12 removed
modified:deno_dist/router/reg-exp-router/router.ts+4 added-2 removed
4 unmodified lines5 import { PATH_ERROR } from './node.ts'6 import type { ParamMap } from './trie.ts'7 import { Trie } from './trie.ts'8 9-const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9+const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())10 11 type HandlerData<T> = [T[], ParamMap | null]12 type Matcher<T> = [RegExp, HandlerData<T>[]]13 73 unmodified lines87 if (!middleware || !routes) {88 throw new Error('Can not add a route since the matcher is already built.')89 }90 91+ if (!methodNames.includes(method)) methodNames.push(method)92+93 if (path === '/*') {94 path = '*'95 }96 68 unmodified lines165 166 private buildAllMatchers(): Record<string, Matcher<T>> {167 const matchers: Record<string, Matcher<T>> = {}168 167- METHOD_NAMES.forEach((method) => {169+ methodNames.forEach((method) => {170 matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]171 })172 173 // Release cache34 unmodified linesmodified:deno_dist/router/static-router/router.ts+15 added
13 unmodified lines141516171819202122232425262728293031323334353637383957 unmodified lines13 unmodified lines this.routes[method.toUpperCase()] = {} }) }
private newRoute(): Record<string, Result<T>> { const route: Record<string, Result<T>> = {} const routeAll = this.routes[METHOD_NAME_ALL] Object.keys(routeAll).forEach((path) => { route[path] = { handlers: [...routeAll[path].handlers], params: {}, } })
return route }
add(method: string, path: string, handler: T) { const { middleware, routes } = this
routes[method] ||= this.newRoute()
if (path === '/*') { path = '*' }
57 unmodified linesmodified:deno_dist/hono.ts+9 added
138 unmodified lines139 })140 return this141 }142 143+ on(method: string, path: string, ...handlers: Handler<P, E, S>[]) {144+ if (!method) return this145+ this.path = path146+ handlers.map((handler) => {147+ this.addRoute(method.toUpperCase(), this.path, handler)148+ })149+ return this150+ }151+152 onError(handler: ErrorHandler<E>) {153 this.errorHandler = handler154 return this155 }109 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+5 added
4 unmodified lines5 const router = new RegExpRouter<string>()6 7 router.add('GET', '/hello', 'get hello')8 router.add('POST', '/hello', 'post hello')9+ router.add('PURGE', '/hello', 'purge hello')10 11 it('get, post hello', async () => {12 let res = router.match('GET', '/hello')13 expect(res).not.toBeNull()2 unmodified lines16 res = router.match('POST', '/hello')17 expect(res).not.toBeNull()18 expect(res?.handlers).toEqual(['post hello'])19 20+ res = router.match('PURGE', '/hello')21+ expect(res).not.toBeNull()22+ expect(res?.handlers).toEqual(['purge hello'])23+24 res = router.match('PUT', '/hello')25 expect(res).toBeNull()26 27 res = router.match('GET', '/')256 unmodified linesmodified:src/router/reg-exp-router/router.ts+4 added-2 removed
4 unmodified lines5 import { PATH_ERROR } from './node'6 import type { ParamMap } from './trie'7 import { Trie } from './trie'8 9-const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9+const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())10 11 type HandlerData<T> = [T[], ParamMap | null]12 type Matcher<T> = [RegExp, HandlerData<T>[]]13 73 unmodified lines87 if (!middleware || !routes) {88 throw new Error('Can not add a route since the matcher is already built.')89 }90 91+ if (!methodNames.includes(method)) methodNames.push(method)92+93 if (path === '/*') {94 path = '*'95 }96 68 unmodified lines165 166 private buildAllMatchers(): Record<string, Matcher<T>> {167 const matchers: Record<string, Matcher<T>> = {}168 167- METHOD_NAMES.forEach((method) => {169+ methodNames.forEach((method) => {170 matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]171 })172 173 // Release cache34 unmodified linesmodified:src/router/smart-router/router.test.ts+12 added-7 removed
9 unmodified lines10 })11 12 router.add('GET', '/hello', 'get hello')13 router.add('POST', '/hello', 'post hello')14+ router.add('PURGE', '/hello', 'purge hello')15 16 it('get, post hello', async () => {17 let res = router.match('GET', '/hello')18 expect(res).not.toBeNull()2 unmodified lines21 res = router.match('POST', '/hello')22 expect(res).not.toBeNull()23 expect(res?.handlers).toEqual(['post hello'])24 25+ res = router.match('PURGE', '/hello')26+ expect(res).not.toBeNull()27+ expect(res?.handlers).toEqual(['purge hello'])28+29 res = router.match('PUT', '/hello')30 expect(res).toBeNull()31 32 res = router.match('GET', '/')39 unmodified lines72 router = new SmartRouter<string>({73 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],74 })75 })71- 76+77 it('Named Param', async () => {78 router.add('GET', '/entry/:id', 'get entry')79 const res = router.match('GET', '/entry/123')80 expect(res).not.toBeNull()81 expect(res?.handlers).toEqual(['get entry'])82 expect(res?.params['id']).toBe('123')83 expect(router.activeRouter).toBeInstanceOf(RegExpRouter)84 })80- 85+86 it('Wildcard', async () => {87 router.add('GET', '/wild/*/card', 'get wildcard')88 const res = router.match('GET', '/wild/xxx/card')89 expect(res).not.toBeNull()90 expect(res?.handlers).toEqual(['get wildcard'])91 })87- 92+93 it('Default', async () => {94 router.add('GET', '/api/abc', 'get api')95 router.add('GET', '/api/*', 'fallback')96 let res = router.match('GET', '/api/abc')2 unmodified lines99 res = router.match('GET', '/api/def')100 expect(res).not.toBeNull()101 expect(res?.handlers).toEqual(['fallback'])102 })98- 103+104 it('Regexp', async () => {105 router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')106 let res = router.match('GET', '/post/20210101/hello')107 expect(res).not.toBeNull()4 unmodified lines112 expect(res).toBeNull()113 res = router.match('GET', '/post/123/123')114 expect(res).toBeNull()115 })111- 116+117 it('/*', async () => {118 router.add('GET', '/api/*', 'auth middleware')119 router.add('GET', '/api', 'top')120 router.add('GET', '/api/posts', 'posts')121 router.add('GET', '/api/*', 'fallback')117- 122+123 let res = router.match('GET', '/api')124 expect(res).not.toBeNull()125 expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])121- 126+127 res = router.match('GET', '/api/posts')128 expect(res).not.toBeNull()129 expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])130 })19 unmodified linesmodified:src/router/static-router/router.test.ts+5 added
3 unmodified lines4567891011122 unmodified lines15161718192021222324252628 unmodified lines3 unmodified lines const router = new StaticRouter<string>()
router.add('GET', '/hello', 'get hello') router.add('POST', '/hello', 'post hello') router.add('PURGE', '/hello', 'purge hello')
it('get, post hello', async () => { let res = router.match('GET', '/hello') expect(res).not.toBeNull()2 unmodified lines res = router.match('POST', '/hello') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['post hello'])
res = router.match('PURGE', '/hello') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['purge hello'])
res = router.match('PUT', '/hello') expect(res).toBeNull()
res = router.match('GET', '/')28 unmodified linesmodified:src/router/static-router/router.ts+15 added
13 unmodified lines14 this.routes[method.toUpperCase()] = {}15 })16 }17 18+ private newRoute(): Record<string, Result<T>> {19+ const route: Record<string, Result<T>> = {}20+ const routeAll = this.routes[METHOD_NAME_ALL]21+ Object.keys(routeAll).forEach((path) => {22+ route[path] = {23+ handlers: [...routeAll[path].handlers],24+ params: {},25+ }26+ })27+28+ return route29+ }30+31 add(method: string, path: string, handler: T) {32 const { middleware, routes } = this33 34+ routes[method] ||= this.newRoute()35+36 if (path === '/*') {37 path = '*'38 }39 57 unmodified linesmodified:src/router/trie-router/router.test.ts+5 added
3 unmodified lines4 const router = new TrieRouter<string>()5 6 router.add('GET', '/hello', 'get hello')7 router.add('POST', '/hello', 'post hello')8+ router.add('PURGE', '/hello', 'purge hello')9 10 it('get, post hello', async () => {11 let res = router.match('GET', '/hello')12 expect(res).not.toBeNull()2 unmodified lines15 res = router.match('POST', '/hello')16 expect(res).not.toBeNull()17 expect(res?.handlers).toEqual(['post hello'])18 19+ res = router.match('PURGE', '/hello')20+ expect(res).not.toBeNull()21+ expect(res?.handlers).toEqual(['purge hello'])22+23 res = router.match('PUT', '/hello')24 expect(res).toBeNull()25 26 res = router.match('GET', '/')141 unmodified linesmodified:src/hono.test.ts+45 added-1 removed
1 unmodified line2 import type { Context } from './context'3 import { Hono } from './hono'4 import { logger } from './middleware/logger'5 import { poweredBy } from './middleware/powered-by'6+import { RegExpRouter } from './router/reg-exp-router'7+import { StaticRouter } from './router/static-router'8+import { TrieRouter } from './router/trie-router'9 import type { Handler, Next } from './types'10 import type { Expect, Equal } from './utils/types'11 12 describe('GET Request', () => {853 unmodified lines866 })867 })868 })869 870+describe('Using other methods with `app.on`', () => {871+ it('Should handle PURGE method with StaticRouter', async () => {872+ const app = new Hono({ router: new StaticRouter() })873+874+ app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))875+876+ const req = new Request('http://localhost/purge', {877+ method: 'PURGE',878+ })879+ const res = await app.request(req)880+ expect(res.status).toBe(202)881+ expect(await res.text()).toBe('Accepted')882+ })883+884+ it('Should handle PURGE method with RegExpRouter', async () => {885+ const app = new Hono({ router: new RegExpRouter() })886+887+ app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))888+889+ const req = new Request('http://localhost/purge', {890+ method: 'PURGE',891+ })892+ const res = await app.request(req)893+ expect(res.status).toBe(202)894+ expect(await res.text()).toBe('Accepted')895+ })896+897+ it('Should handle PURGE method with TrieRouter', async () => {898+ const app = new Hono({ router: new TrieRouter() })899+900+ app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))901+902+ const req = new Request('http://localhost/purge', {903+ method: 'PURGE',904+ })905+ const res = await app.request(req)906+ expect(res.status).toBe(202)907+ expect(await res.text()).toBe('Accepted')908+ })909+})910+911 describe('Multiple handler', () => {912 describe('handler + handler', () => {913 const app = new Hono()914 414 unmodified lines1329 expect(await res.text()).toBe('Post id is 123')1330 })1331 })1332 1289-describe.only('Show routes', () => {1333+describe('Show routes', () => {1334 const app = new Hono()1335 jest.spyOn(console, 'log')1336 it('Should call `console.log()` with `app.showRoutes()`', async () => {1337 app.get('/', (c) => c.text('/'))5 unmodified linesmodified:src/hono.ts+9 added
138 unmodified lines139 })140 return this141 }142 143+ on(method: string, path: string, ...handlers: Handler<P, E, S>[]) {144+ if (!method) return this145+ this.path = path146+ handlers.map((handler) => {147+ this.addRoute(method.toUpperCase(), this.path, handler)148+ })149+ return this150+ }151+152 onError(handler: ErrorHandler<E>) {153 this.errorHandler = handler154 return this155 }109 unmodified lines