Skip to content
Myr

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

11 files+128 added−12 removed

modified:deno_dist/router/reg-exp-router/router.ts+4 added-2 removed
4 unmodified lines
5import { PATH_ERROR } from './node.ts'6import type { ParamMap } from './trie.ts'7import { Trie } from './trie.ts'89const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())1011type HandlerData<T> = [T[], ParamMap | null]12type Matcher<T> = [RegExp, HandlerData<T>[]]13
73 unmodified lines
87 if (!middleware || !routes) {88 throw new Error('Can not add a route since the matcher is already built.')89 }9091 if (!methodNames.includes(method)) methodNames.push(method)9293 if (path === '/*') {94 path = '*'95 }96
68 unmodified lines
165166 private buildAllMatchers(): Record<string, Matcher<T>> {167 const matchers: Record<string, Matcher<T>> = {}168167 METHOD_NAMES.forEach((method) => {169 methodNames.forEach((method) => {170 matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]171 })172173 // Release cache
34 unmodified lines
modified:deno_dist/router/static-router/router.ts+15 added
modified:deno_dist/hono.ts+9 added
138 unmodified lines
139 })140 return this141 }142143 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 }151152 onError(handler: ErrorHandler<E>) {153 this.errorHandler = handler154 return this155 }
109 unmodified lines
modified:src/router/reg-exp-router/router.test.ts+5 added
4 unmodified lines
5 const router = new RegExpRouter<string>()67 router.add('GET', '/hello', 'get hello')8 router.add('POST', '/hello', 'post hello')9 router.add('PURGE', '/hello', 'purge hello')1011 it('get, post hello', async () => {12 let res = router.match('GET', '/hello')13 expect(res).not.toBeNull()
2 unmodified lines
16 res = router.match('POST', '/hello')17 expect(res).not.toBeNull()18 expect(res?.handlers).toEqual(['post hello'])1920 res = router.match('PURGE', '/hello')21 expect(res).not.toBeNull()22 expect(res?.handlers).toEqual(['purge hello'])2324 res = router.match('PUT', '/hello')25 expect(res).toBeNull()2627 res = router.match('GET', '/')
256 unmodified lines
modified:src/router/reg-exp-router/router.ts+4 added-2 removed
4 unmodified lines
5import { PATH_ERROR } from './node'6import type { ParamMap } from './trie'7import { Trie } from './trie'89const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())1011type HandlerData<T> = [T[], ParamMap | null]12type Matcher<T> = [RegExp, HandlerData<T>[]]13
73 unmodified lines
87 if (!middleware || !routes) {88 throw new Error('Can not add a route since the matcher is already built.')89 }9091 if (!methodNames.includes(method)) methodNames.push(method)9293 if (path === '/*') {94 path = '*'95 }96
68 unmodified lines
165166 private buildAllMatchers(): Record<string, Matcher<T>> {167 const matchers: Record<string, Matcher<T>> = {}168167 METHOD_NAMES.forEach((method) => {169 methodNames.forEach((method) => {170 matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]171 })172173 // Release cache
34 unmodified lines
modified:src/router/smart-router/router.test.ts+12 added-7 removed
9 unmodified lines
10 })1112 router.add('GET', '/hello', 'get hello')13 router.add('POST', '/hello', 'post hello')14 router.add('PURGE', '/hello', 'purge hello')1516 it('get, post hello', async () => {17 let res = router.match('GET', '/hello')18 expect(res).not.toBeNull()
2 unmodified lines
21 res = router.match('POST', '/hello')22 expect(res).not.toBeNull()23 expect(res?.handlers).toEqual(['post hello'])2425 res = router.match('PURGE', '/hello')26 expect(res).not.toBeNull()27 expect(res?.handlers).toEqual(['purge hello'])2829 res = router.match('PUT', '/hello')30 expect(res).toBeNull()3132 res = router.match('GET', '/')
39 unmodified lines
72 router = new SmartRouter<string>({73 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],74 })75 })71 7677 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 8586 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 9293 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 lines
99 res = router.match('GET', '/api/def')100 expect(res).not.toBeNull()101 expect(res?.handlers).toEqual(['fallback'])102 })98 103104 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 lines
112 expect(res).toBeNull()113 res = router.match('GET', '/post/123/123')114 expect(res).toBeNull()115 })111 116117 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 122123 let res = router.match('GET', '/api')124 expect(res).not.toBeNull()125 expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])121 126127 res = router.match('GET', '/api/posts')128 expect(res).not.toBeNull()129 expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])130 })
19 unmodified lines
modified:src/router/static-router/router.test.ts+5 added
modified:src/router/static-router/router.ts+15 added
13 unmodified lines
14 this.routes[method.toUpperCase()] = {}15 })16 }1718 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 })2728 return route29 }3031 add(method: string, path: string, handler: T) {32 const { middleware, routes } = this3334 routes[method] ||= this.newRoute()3536 if (path === '/*') {37 path = '*'38 }39
57 unmodified lines
modified:src/router/trie-router/router.test.ts+5 added
3 unmodified lines
4 const router = new TrieRouter<string>()56 router.add('GET', '/hello', 'get hello')7 router.add('POST', '/hello', 'post hello')8 router.add('PURGE', '/hello', 'purge hello')910 it('get, post hello', async () => {11 let res = router.match('GET', '/hello')12 expect(res).not.toBeNull()
2 unmodified lines
15 res = router.match('POST', '/hello')16 expect(res).not.toBeNull()17 expect(res?.handlers).toEqual(['post hello'])1819 res = router.match('PURGE', '/hello')20 expect(res).not.toBeNull()21 expect(res?.handlers).toEqual(['purge hello'])2223 res = router.match('PUT', '/hello')24 expect(res).toBeNull()2526 res = router.match('GET', '/')
141 unmodified lines
modified:src/hono.test.ts+45 added-1 removed
1 unmodified line
2import type { Context } from './context'3import { Hono } from './hono'4import { logger } from './middleware/logger'5import { poweredBy } from './middleware/powered-by'6import { RegExpRouter } from './router/reg-exp-router'7import { StaticRouter } from './router/static-router'8import { TrieRouter } from './router/trie-router'9import type { Handler, Next } from './types'10import type { Expect, Equal } from './utils/types'1112describe('GET Request', () => {
853 unmodified lines
866 })867 })868})869870describe('Using other methods with `app.on`', () => {871 it('Should handle PURGE method with StaticRouter', async () => {872 const app = new Hono({ router: new StaticRouter() })873874 app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))875876 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 })883884 it('Should handle PURGE method with RegExpRouter', async () => {885 const app = new Hono({ router: new RegExpRouter() })886887 app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))888889 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 })896897 it('Should handle PURGE method with TrieRouter', async () => {898 const app = new Hono({ router: new TrieRouter() })899900 app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))901902 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})910911describe('Multiple handler', () => {912 describe('handler + handler', () => {913 const app = new Hono()914
414 unmodified lines
1329 expect(await res.text()).toBe('Post id is 123')1330 })1331})13321289describe.only('Show routes', () => {1333describe('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 lines
modified:src/hono.ts+9 added
138 unmodified lines
139 })140 return this141 }142143 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 }151152 onError(handler: ErrorHandler<E>) {153 this.errorHandler = handler154 return this155 }
109 unmodified lines