feat(app): `app.routerName()` (#1105)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(context): `c.routerName()` * chore: denoify * Enable to get router name via `app.routerName`. (#1110) ---------
authored by Yusuke Wada · committed by GitHub · parent 2cdfcd8 · Browse files · 17 files·+44 added−2 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
17 files+44 added−2 removed
- tests:+15 added−0 removed
- other:+29 added−2 removed
Provenance
- Commit
390d05b- Tree
25b66e6- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
2cdfcd8
17 files changed+44 added−2 removed
modified:deno_dist/router/linear-router/router.ts+2 added-1 removed
123445678910111213131 unmodified linesExpand allimport type { Router, Result } from '../../router.ts'import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router.ts'
type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] };type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }
const splitPathRe = /\/(:\w+(?:{[^}]+})?)|\/[^\/\?]+|(\?)/gconst splitByStarRe = /\*/export class LinearRouter<T> implements Router<T> { name: string = 'LinearRouter' routes: [string, string, T][] = []
add(method: string, path: string, handler: T) { if (path.charCodeAt(path.length - 1) === 63) {131 unmodified linesExpand allmodified:deno_dist/router/pattern-router/router.ts+1 added
2 unmodified lines3 4 type Route<T> = [RegExp, string, T] // [pattern, method, handler]5 6 export class PatternRouter<T> implements Router<T> {7+ name: string = 'PatternRouter'8 private routes: Route<T>[] = []9 private dNames: Record<string, number> = {} // Short name of duplicatedNames10 11 add(method: string, path: string, handler: T) {59 unmodified linesmodified:deno_dist/router/reg-exp-router/router.ts+1 added
99 unmodified lines100 return undefined101 }102 103 export class RegExpRouter<T> implements Router<T> {104+ name: string = 'RegExpRouter'105 middleware?: Record<string, Record<string, T[]>>106 routes?: Record<string, Record<string, T[]>>107 108 constructor() {151 unmodified linesmodified:deno_dist/router/smart-router/router.ts+4 added
1 unmodified line2 import type { Router, Result } from '../../router.ts'3 import { UnsupportedPathError } from '../../router.ts'4 5 export class SmartRouter<T> implements Router<T> {6+ name: string = 'SmartRouter'7 routers: Router<T>[] = []8 routes?: [string, string, T][] = []9 10 constructor(init: Pick<SmartRouter<T>, 'routers'>) {41 unmodified lines52 // not found53 throw new Error('Fatal error')54 }55 56+ // e.g. "SmartRouter + RegExpRouter"57+ this.name = `SmartRouter + ${this.activeRouter.name}`58+59 return res || null60 }61 62 get activeRouter() {7 unmodified linesmodified:deno_dist/router/trie-router/router.ts+1 added
1234567891018 unmodified linesimport type { Result, Router } from '../../router.ts'import { checkOptionalParameter } from '../../utils/url.ts'import { Node } from './node.ts'
export class TrieRouter<T> implements Router<T> { name: string = 'TrieRouter' node: Node<T>
constructor() { this.node = new Node()18 unmodified linesmodified:deno_dist/context.ts+3 added
63 unmodified lines64 executionCtx?: FetchEvent | ExecutionContext | undefined65 notFoundHandler?: NotFoundHandler<E>66 path?: string67 paramData?: Record<string, string>68+ routerName?: string69 }70 71 export class Context<72 // eslint-disable-next-line @typescript-eslint/no-explicit-any4 unmodified lines77 > {78 env: E['Bindings'] = {}79 finalized: boolean = false80 error: Error | undefined = undefined81+ routerName?: string | undefined82 83 // eslint-disable-next-line @typescript-eslint/no-explicit-any84 private _req?: HonoRequest<any, any>85 private _status: StatusCode = 20014 unmodified lines100 if (options) {101 this._exCtx = options.executionCtx102 this._path = options.path ?? '/'103 this._pData = options.paramData104+ this.routerName = options.routerName105 this.env = options.env106 if (options.notFoundHandler) {107 this.notFoundHandler = options.notFoundHandler108 }294 unmodified linesmodified:deno_dist/hono-base.ts+1 added
230 unmodified lines231 executionCtx: eventOrExecutionCtx,232 notFoundHandler: this.notFoundHandler,233 path,234 paramData,235+ routerName: this.router.name,236 })237 238 // Do not `compose` if it has only one handler239 if (result?.handlers.length === 1) {87 unmodified linesmodified:deno_dist/router.ts+1 added
123456789106 unmodified linesexport const METHOD_NAME_ALL = 'ALL' as constexport const METHOD_NAME_ALL_LOWERCASE = 'all' as constexport const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const
export interface Router<T> { name: string add(method: string, path: string, handler: T): void match(method: string, path: string): Result<T> | null}
6 unmodified linesmodified:src/router/linear-router/router.ts+2 added-1 removed
1 import type { Router, Result } from '../../router'2 import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'3 4-type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] };4+type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }5 6 const splitPathRe = /\/(:\w+(?:{[^}]+})?)|\/[^\/\?]+|(\?)/g7 const splitByStarRe = /\*/8 export class LinearRouter<T> implements Router<T> {9+ name: string = 'LinearRouter'10 routes: [string, string, T][] = []11 12 add(method: string, path: string, handler: T) {13 if (path.charCodeAt(path.length - 1) === 63) {131 unmodified linesmodified:src/router/pattern-router/router.ts+1 added
2 unmodified lines3 4 type Route<T> = [RegExp, string, T] // [pattern, method, handler]5 6 export class PatternRouter<T> implements Router<T> {7+ name: string = 'PatternRouter'8 private routes: Route<T>[] = []9 private dNames: Record<string, number> = {} // Short name of duplicatedNames10 11 add(method: string, path: string, handler: T) {59 unmodified linesmodified:src/router/reg-exp-router/router.ts+1 added
99 unmodified lines100 return undefined101 }102 103 export class RegExpRouter<T> implements Router<T> {104+ name: string = 'RegExpRouter'105 middleware?: Record<string, Record<string, T[]>>106 routes?: Record<string, Record<string, T[]>>107 108 constructor() {151 unmodified linesmodified:src/router/smart-router/router.test.ts+2 added
16 unmodified lines17 expect(res).not.toBeNull()18 expect(res?.handlers).toEqual(['get entry'])19 expect(res?.params['id']).toBe('123')20 expect(router.activeRouter).toBeInstanceOf(RegExpRouter)21+ expect(router.name).toBe('SmartRouter + RegExpRouter')22 })23 24 it('Wildcard', async () => {25 router.add('GET', '/wild/*/card', 'get wildcard')56 unmodified lines82 expect(res?.handlers).toEqual(['get user entries', 'get entry'])83 expect(res?.params['user']).toBe('entry')84 expect(res?.params['name']).toBe('entries')85 expect(router.activeRouter).toBeInstanceOf(TrieRouter)86+ expect(router.name).toBe('SmartRouter + TrieRouter')87 })88 })modified:src/router/smart-router/router.ts+4 added
1 unmodified line2 import type { Router, Result } from '../../router'3 import { UnsupportedPathError } from '../../router'4 5 export class SmartRouter<T> implements Router<T> {6+ name: string = 'SmartRouter'7 routers: Router<T>[] = []8 routes?: [string, string, T][] = []9 10 constructor(init: Pick<SmartRouter<T>, 'routers'>) {41 unmodified lines52 // not found53 throw new Error('Fatal error')54 }55 56+ // e.g. "SmartRouter + RegExpRouter"57+ this.name = `SmartRouter + ${this.activeRouter.name}`58+59 return res || null60 }61 62 get activeRouter() {7 unmodified linesmodified:src/router/trie-router/router.ts+1 added
1 unmodified line2 import { checkOptionalParameter } from '../../utils/url'3 import { Node } from './node'4 5 export class TrieRouter<T> implements Router<T> {6+ name: string = 'TrieRouter'7 node: Node<T>8 9 constructor() {10 this.node = new Node()18 unmodified linesmodified:src/hono-base.ts+5 added
192 unmodified lines193 )194 })195 }196 197+ get routerName() {198+ this.matchRoute('GET', '/')199+ return this.router.name200+ }201+202 private addRoute(method: string, path: string, handler: H) {203 method = method.toUpperCase()204 if (this._basePath) {205 path = mergePath(this._basePath, path)125 unmodified linesmodified:src/hono.test.ts+13 added
1908 unmodified lines1909 type: undefined,1910 })1911 })1912 })1913+1914+describe('Router Name', () => {1915+ it('Should return the correct router name', async () => {1916+ const app = new Hono({1917+ router: new RegExpRouter(),1918+ })1919+ app.get('/router-name', (c) => {1920+ return c.text(app.routerName ?? 'N/A')1921+ })1922+ const res = await app.request('/router-name')1923+ expect(await res.text()).toBe('RegExpRouter')1924+ })1925+})modified:src/router.ts+1 added
1 unmodified line2 export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3 export const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const4 5 export interface Router<T> {6+ name: string7 add(method: string, path: string, handler: T): void8 match(method: string, path: string): Result<T> | null9 }10 6 unmodified lines