refactor: directory structure (#114)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: move trie-router * refactor: mv node.ts * refactor: do not use `test` directory * fix eslint target
authored by Yusuke Wada · committed by GitHub · parent 4c76a7d · Browse files · 16 files·+932 added−928 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+932 added−928 removed
- tests:+787 added−787 removed
- other:+145 added−141 removed
Provenance
- Commit
0a6afc2- Tree
ff8dde8- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
4c76a7d
16 files changed+932 added−928 removed
added:src/router/trie-router/index.ts+1 added
1export { TrieRouter } from './router'added:src/router/trie-router/node.test.ts+193 added
1+import { Node } from './node'2+3+describe('Root Node', () => {4+ const node = new Node()5+ node.insert('get', '/', 'get root')6+ it('get /', () => {7+ const res = node.search('get', '/')8+ expect(res).not.toBeNull()9+ expect(res.handler).toBe('get root')10+ expect(node.search('get', '/hello')).toBeNull()11+ })12+})13+14+describe('Root Node is not defined', () => {15+ const node = new Node()16+ node.insert('get', '/hello', 'get hello')17+ it('get /', () => {18+ expect(node.search('get', '/')).toBeNull()19+ })20+})21+22+describe('All with *', () => {23+ const node = new Node()24+ node.insert('get', '*', 'get all')25+ it('get /', () => {26+ expect(node.search('get', '/')).not.toBeNull()27+ expect(node.search('get', '/hello')).not.toBeNull()28+ })29+})30+31+describe('Basic Usage', () => {32+ const node = new Node()33+ node.insert('get', '/hello', 'get hello')34+ node.insert('post', '/hello', 'post hello')35+ node.insert('get', '/hello/foo', 'get hello foo')36+37+ it('get, post /hello', () => {38+ expect(node.search('get', '/')).toBeNull()39+ expect(node.search('post', '/')).toBeNull()40+41+ expect(node.search('get', '/hello').handler).toBe('get hello')42+ expect(node.search('post', '/hello').handler).toBe('post hello')43+ expect(node.search('put', '/hello')).toBeNull()44+ })45+ it('get /nothing', () => {46+ expect(node.search('get', '/nothing')).toBeNull()47+ })48+ it('/hello/foo, /hello/bar', () => {49+ expect(node.search('get', '/hello/foo').handler).toBe('get hello foo')50+ expect(node.search('post', '/hello/foo')).toBeNull()51+ expect(node.search('get', '/hello/bar')).toBeNull()52+ })53+ it('/hello/foo/bar', () => {54+ expect(node.search('get', '/hello/foo/bar')).toBeNull()55+ })56+})57+58+describe('Name path', () => {59+ const node = new Node()60+ node.insert('get', '/entry/:id', 'get entry')61+ node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')62+ node.insert('get', '/map/:location/events', 'get events')63+64+ it('get /entry/123', () => {65+ const res = node.search('get', '/entry/123')66+ expect(res).not.toBeNull()67+ expect(res.handler).toBe('get entry')68+ expect(res.params).not.toBeNull()69+ expect(res.params['id']).toBe('123')70+ expect(res.params['id']).not.toBe('1234')71+ })72+73+ it('get /entry/456/comment', () => {74+ const res = node.search('get', '/entry/456/comment')75+ expect(res).toBeNull()76+ })77+78+ it('get /entry/789/comment/123', () => {79+ const res = node.search('get', '/entry/789/comment/123')80+ expect(res).not.toBeNull()81+ expect(res.handler).toBe('get comment')82+ expect(res.params['id']).toBe('789')83+ expect(res.params['comment_id']).toBe('123')84+ })85+86+ it('get /map/:location/events', () => {87+ const res = node.search('get', '/map/yokohama/events')88+ expect(res).not.toBeNull()89+ expect(res.handler).toBe('get events')90+ expect(res.params['location']).toBe('yokohama')91+ })92+})93+94+describe('Wildcard', () => {95+ const node = new Node()96+ node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')97+ it('/wildcard-abc/xxxxxx/wildcard-efg', () => {98+ const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')99+ expect(res).not.toBeNull()100+ expect(res.handler).toBe('wildcard')101+ })102+ node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard')103+ it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => {104+ const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk')105+ expect(res).not.toBeNull()106+ expect(res.handler).toBe('wildcard')107+ })108+})109+110+describe('Regexp', () => {111+ const node = new Node()112+ node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')113+ it('/regexp-abc/123/comment/abc', () => {114+ const res = node.search('get', '/regex-abc/123/comment/abc')115+ expect(res).not.toBeNull()116+ expect(res.handler).toBe('regexp')117+ expect(res.params['id']).toBe('123')118+ expect(res.params['comment_id']).toBe('abc')119+ })120+ it('/regexp-abc/abc', () => {121+ const res = node.search('get', '/regex-abc/abc')122+ expect(res).toBeNull()123+ })124+ it('/regexp-abc/123/comment/123', () => {125+ const res = node.search('get', '/regex-abc/123/comment/123')126+ expect(res).toBeNull()127+ })128+})129+130+describe('All', () => {131+ const node = new Node()132+ node.insert('ALL', '/all-methods', 'all methods') // ALL133+ it('/all-methods', () => {134+ let res = node.search('get', '/all-methods')135+ expect(res).not.toBeNull()136+ expect(res.handler).toBe('all methods')137+ res = node.search('put', '/all-methods')138+ expect(res).not.toBeNull()139+ expect(res.handler).toBe('all methods')140+ })141+})142+143+describe('Special Wildcard', () => {144+ const node = new Node()145+ node.insert('ALL', '*', 'match all')146+147+ it('/foo', () => {148+ const res = node.search('get', '/foo')149+ expect(res).not.toBeNull()150+ expect(res.handler).toBe('match all')151+ })152+ it('/hello', () => {153+ const res = node.search('get', '/hello')154+ expect(res).not.toBeNull()155+ expect(res.handler).toBe('match all')156+ })157+ it('/hello/foo', () => {158+ const res = node.search('get', '/hello/foo')159+ expect(res).not.toBeNull()160+ expect(res.handler).toBe('match all')161+ })162+})163+164+describe('Special Wildcard deeply', () => {165+ const node = new Node()166+ node.insert('ALL', '/hello/*', 'match hello')167+ it('/hello', () => {168+ const res = node.search('get', '/hello')169+ expect(res).not.toBeNull()170+ expect(res.handler).toBe('match hello')171+ })172+ it('/hello/foo', () => {173+ const res = node.search('get', '/hello/foo')174+ expect(res).not.toBeNull()175+ expect(res.handler).toBe('match hello')176+ })177+})178+179+describe('Default with wildcard', () => {180+ const node = new Node()181+ node.insert('ALL', '/api/abc', 'match api')182+ node.insert('ALL', '/api/*', 'fallback')183+ it('/api/abc', () => {184+ const res = node.search('get', '/api/abc')185+ expect(res).not.toBeNull()186+ expect(res.handler).toBe('match api')187+ })188+ it('/api/def', () => {189+ const res = node.search('get', '/api/def')190+ expect(res).not.toBeNull()191+ expect(res.handler).toBe('fallback')192+ })193+})added:src/router/trie-router/node.ts+120 added
1+import type { Pattern } from '../../utils/url'2+import { splitPath, getPattern } from '../../utils/url'3+import { Result, METHOD_NAME_OF_ALL } from '../../router'4+5+const noRoute = (): null => {6+ return null7+}8+9+export class Node<T> {10+ method: Record<string, T>11+ handler: T12+ children: Record<string, Node<T>>13+ middlewares: []14+ patterns: Pattern[]15+16+ constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {17+ this.children = children || {}18+ this.method = {}19+ if (method && handler) {20+ this.method[method] = handler21+ }22+ this.middlewares = []23+ this.patterns = []24+ }25+26+ insert(method: string, path: string, handler: T): Node<T> {27+ // eslint-disable-next-line @typescript-eslint/no-this-alias28+ let curNode: Node<T> = this29+ const parts = splitPath(path)30+ for (let i = 0, len = parts.length; i < len; i++) {31+ const p: string = parts[i]32+ if (Object.keys(curNode.children).includes(p)) {33+ curNode = curNode.children[p]34+ continue35+ }36+ curNode.children[p] = new Node()37+ const pattern = getPattern(p)38+ if (pattern) {39+ curNode.patterns.push(pattern)40+ }41+42+ curNode = curNode.children[p]43+ }44+ curNode.method[method] = handler45+ return curNode46+ }47+48+ search(method: string, path: string): Result<T> {49+ // eslint-disable-next-line @typescript-eslint/no-this-alias50+ let curNode: Node<T> = this51+52+ const params: { [key: string]: string } = {}53+ const parts = splitPath(path)54+55+ for (let i = 0, len = parts.length; i < len; i++) {56+ const p: string = parts[i]57+58+ // '*' => match any path59+ // /api/* => default wildcard match60+ if (curNode.children['*'] && !curNode.children[p]) {61+ const astNode = curNode.children['*']62+ if (Object.keys(astNode.children).length === 0) {63+ curNode = astNode64+ break65+ }66+ }67+68+ const nextNode = curNode.children[p]69+70+ if (nextNode) {71+ curNode = nextNode72+ // '/hello/*' => match '/hello'73+ if (!(i == len - 1 && nextNode.children['*'])) {74+ continue75+ }76+ }77+78+ let isWildcard = false79+ let isParamMatch = false80+81+ for (let j = 0, len = curNode.patterns.length; j < len; j++) {82+ const pattern = curNode.patterns[j]83+84+ // Wildcard85+ // '/hello/*/foo' => match /hello/bar/foo86+ if (pattern === '*') {87+ curNode = curNode.children['*']88+ isWildcard = true89+ break90+ }91+92+ // Named match93+ const [key, name, matcher] = pattern94+ if (p !== '' && (matcher === true || matcher.test(p))) {95+ params[name] = p96+ curNode = curNode.children[key]97+ isParamMatch = true98+ break99+ }100+ return noRoute()101+ }102+103+ if (isWildcard && i === len - 1) {104+ break105+ }106+107+ if (isWildcard === false && isParamMatch === false) {108+ return noRoute()109+ }110+ }111+112+ const handler = curNode.method[METHOD_NAME_OF_ALL] || curNode.method[method]113+114+ if (!handler) {115+ return noRoute()116+ }117+118+ return new Result<T>(handler, params)119+ }120+}added:src/router/trie-router/router.test.ts+67 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { TrieRouter } from './router'
describe('Basic Usage', () => { const router = new TrieRouter<string>()
router.add('GET', '/hello', 'get hello') router.add('POST', '/hello', 'post hello')
it('get, post hello', async () => { let res = router.match('GET', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get hello')
res = router.match('POST', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('post hello')
res = router.match('PUT', '/hello') expect(res).toBeNull()
res = router.match('GET', '/') expect(res).toBeNull() })})
describe('Complex', () => { const router = new TrieRouter<string>()
it('Named Param', async () => { router.add('GET', '/entry/:id', 'get entry') const res = router.match('GET', '/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('get entry') expect(res.params['id']).toBe('123') })
it('Wildcard', async () => { router.add('GET', '/wild/*/card', 'get wildcard') const res = router.match('GET', '/wild/xxx/card') expect(res).not.toBeNull() expect(res.handler).toBe('get wildcard') })
it('Default', async () => { router.add('GET', '/api/abc', 'get api') router.add('GET', '/api/*', 'fallback') let res = router.match('GET', '/api/abc') expect(res).not.toBeNull() expect(res.handler).toBe('get api') res = router.match('GET', '/api/def') expect(res).not.toBeNull() expect(res.handler).toBe('fallback') })
it('Regexp', async () => { router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post') let res = router.match('GET', '/post/20210101/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get post') expect(res.params['date']).toBe('20210101') expect(res.params['title']).toBe('hello') res = router.match('GET', '/post/onetwothree') expect(res).toBeNull() res = router.match('GET', '/post/123/123') expect(res).toBeNull() })})added:src/router/trie-router/router.ts+20 added
1234567891011121314151617181920import { Router } from '../../router'import type { Result } from '../../router'import { Node } from './node'
export class TrieRouter<T> extends Router<T> { node: Node<T>
constructor() { super() this.node = new Node() }
add(method: string, path: string, handler: T) { this.node.insert(method, path, handler) }
match(method: string, path: string): Result<T> | null { return this.node.search(method, path) }}added:src/compose.test.ts+47 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import { compose } from './compose'
type C = { req: { [key: string]: string } res: { [key: string]: string }}
describe('compose middleware', () => { const middleware: Function[] = []
const a = async (c: C, next: Function) => { c.req['log'] = 'log' await next() } middleware.push(a)
const b = async (c: C, next: Function) => { await next() c.res['headers'] = `${c.res.headers}-custom-header` } middleware.push(b)
const handler = async (c: C, next: Function) => { c.req['log'] = `${c.req.log} message` await next() c.res = { message: 'new response' } } middleware.push(handler)
const request = {} const response = {}
it('Request', async () => { const c: C = { req: request, res: response } const composed = compose<C>(middleware) await composed(c) expect(c.req['log']).not.toBeNull() expect(c.req['log']).toBe('log message') }) it('Response', async () => { const c: C = { req: request, res: response } const composed = compose(middleware) await composed(c) expect(c.res['header']).not.toBeNull() expect(c.res['message']).toBe('new response') })})added:src/context.test.ts+98 added
1+import { Context } from './context'2+3+describe('Context', () => {4+ const req = new Request('http://localhost/')5+ const c = new Context(req)6+7+ it('c.text()', async () => {8+ const res = c.text('text in c', 201, { 'X-Custom': 'Message' })9+ expect(res.status).toBe(201)10+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=UTF-8')11+ expect(await res.text()).toBe('text in c')12+ expect(res.headers.get('X-Custom')).toBe('Message')13+ })14+15+ it('c.json()', async () => {16+ const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })17+ expect(res.status).toBe(201)18+ expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')19+ const text = await res.text()20+ const object = JSON.parse(text)21+ expect(object.message).toBe('Hello')22+ expect(res.headers.get('X-Custom')).toBe('Message')23+ })24+25+ it('c.html()', async () => {26+ const res = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })27+ expect(res.status).toBe(201)28+ expect(res.headers.get('Content-Type')).toMatch('text/html')29+ expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')30+ expect(res.headers.get('X-Custom')).toBe('Message')31+ })32+33+ it('c.redirect()', async () => {34+ let res = c.redirect('/destination')35+ expect(res.status).toBe(302)36+ expect(res.headers.get('Location')).toMatch(/^https?:\/\/.+\/destination$/)37+ res = c.redirect('https://example.com/destination')38+ expect(res.status).toBe(302)39+ expect(res.headers.get('Location')).toBe('https://example.com/destination')40+ })41+42+ it('c.header()', async () => {43+ c.header('X-Foo', 'Bar')44+ const res = c.body('Hi')45+ const foo = res.headers.get('X-Foo')46+ expect(foo).toBe('Bar')47+ })48+49+ it('c.status() and c.statusText()', async () => {50+ c.status(201)51+ const res = c.body('Hi')52+ expect(res.status).toBe(201)53+ expect(res.statusText).toBe('Created')54+ })55+56+ it('Complext pattern', async () => {57+ c.status(404)58+ const res = c.json({ hono: 'great app' })59+ expect(res.status).toBe(404)60+ expect(res.statusText).toBe('Not Found')61+ expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')62+ const obj: { [key: string]: string } = await res.json()63+ expect(obj['hono']).toBe('great app')64+ })65+66+ it('Content-Length', async () => {67+ let res = c.text('abcdefg')68+ expect(res.headers.get('Content-Length')).toBe('7')69+ res = c.text('炎')70+ expect(res.headers.get('Content-Length')).toBe('3')71+ })72+73+ it('Headers, status, statusText', async () => {74+ c.header('X-Custom1', 'Message1')75+ c.header('X-Custom2', 'Message2')76+ c.status(200)77+ const res = c.newResponse('this is body', {78+ status: 201,79+ headers: {80+ 'X-Custom3': 'Message3',81+ 'X-Custom2': 'Message2-Override',82+ },83+ })84+ expect(res.headers.get('X-Custom1')).toBe('Message1')85+ expect(res.headers.get('X-Custom2')).toBe('Message2-Override')86+ expect(res.headers.get('X-Custom3')).toBe('Message3')87+ expect(res.status).toBe(201)88+ expect(await res.text()).toBe('this is body')89+90+ // res is already setted.91+ c.res = res92+ c.header('X-Custom4', 'Message4')93+ c.status(202)94+ expect(c.res.headers.get('X-Custom4')).toBe('Message4')95+ expect(c.res.status).toBe(201)96+ expect(c.res.statusText).toBe('OK')97+ })98+})added:src/hono.test.ts+382 added
1+import { Hono } from './hono'2+3+describe('GET Request', () => {4+ const app = new Hono()5+6+ app.get('/hello', () => {7+ return new Response('hello', {8+ status: 200,9+ statusText: 'Hono is OK',10+ })11+ })12+13+ app.get('/hello-with-shortcuts', (c) => {14+ c.header('X-Custom', 'This is Hono')15+ c.status(201)16+ return c.html('<h1>Hono!!!</h1>')17+ })18+19+ app.notFound = () => {20+ return new Response('not found', {21+ status: 404,22+ })23+ }24+25+ it('GET /hello is ok', async () => {26+ const req = new Request('http://localhost/hello')27+ const res = await app.dispatch(req)28+ expect(res).not.toBeNull()29+ expect(res.status).toBe(200)30+ expect(res.statusText).toBe('Hono is OK')31+ expect(await res.text()).toBe('hello')32+ })33+34+ it('GET /hell-with-shortcuts is ok', async () => {35+ const req = new Request('http://localhost/hello-with-shortcuts')36+ const res = await app.dispatch(req)37+ expect(res).not.toBeNull()38+ expect(res.status).toBe(201)39+ expect(res.statusText).toBe('Created')40+ expect(res.headers.get('X-Custom')).toBe('This is Hono')41+ expect(res.headers.get('Content-Type')).toMatch(/text\/html/)42+ expect(await res.text()).toBe('<h1>Hono!!!</h1>')43+ })44+45+ it('GET / is not found', async () => {46+ const req = new Request('http://localhost/')47+ const res = await app.dispatch(req)48+ expect(res).not.toBeNull()49+ expect(res.status).toBe(404)50+ })51+})52+53+describe('strict parameter', () => {54+ describe('strict is true with not slash', () => {55+ const app = new Hono()56+57+ app.get('/hello', (c) => {58+ return c.text('/hello')59+ })60+61+ it('/hello/ is not found', async () => {62+ let req = new Request('http://localhost/hello')63+ let res = await app.dispatch(req)64+ expect(res).not.toBeNull()65+ expect(res.status).toBe(200)66+ req = new Request('http://localhost/hello/')67+ res = await app.dispatch(req)68+ expect(res).not.toBeNull()69+ expect(res.status).toBe(404)70+ })71+ })72+73+ describe('strict is true with slash', () => {74+ const app = new Hono()75+76+ app.get('/hello/', (c) => {77+ return c.text('/hello/')78+ })79+80+ it('/hello is not found', async () => {81+ let req = new Request('http://localhost/hello/')82+ let res = await app.dispatch(req)83+ expect(res).not.toBeNull()84+ expect(res.status).toBe(200)85+ req = new Request('http://localhost/hello')86+ res = await app.dispatch(req)87+ expect(res).not.toBeNull()88+ expect(res.status).toBe(404)89+ })90+ })91+92+ describe('strict is false', () => {93+ const app = new Hono({ strict: false })94+95+ app.get('/hello', (c) => {96+ return c.text('/hello')97+ })98+99+ it('/hello and /hello/ are treated as the same', async () => {100+ let req = new Request('http://localhost/hello')101+ let res = await app.dispatch(req)102+ expect(res).not.toBeNull()103+ expect(res.status).toBe(200)104+ req = new Request('http://localhost/hello/')105+ res = await app.dispatch(req)106+ expect(res).not.toBeNull()107+ expect(res.status).toBe(200)108+ })109+ })110+})111+112+describe('Routing', () => {113+ const app = new Hono()114+115+ it('Return it self', async () => {116+ const appRes = app.get('/', () => new Response('get /'))117+ expect(appRes).not.toBeUndefined()118+ appRes.delete('/', () => new Response('delete /'))119+ const req = new Request('http://localhost/', { method: 'DELETE' })120+ const res = await appRes.dispatch(req)121+ expect(res).not.toBeNull()122+ expect(res.status).toBe(200)123+ expect(await res.text()).toBe('delete /')124+ })125+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)141+ expect(await res.text()).toBe('get /book')142+143+ req = new Request('http://localhost/book/123', { method: 'GET' })144+ res = await app.dispatch(req)145+ expect(res.status).toBe(200)146+ expect(await res.text()).toBe('get /book/123')147+148+ req = new Request('http://localhost/book', { method: 'POST' })149+ res = await app.dispatch(req)150+ expect(res.status).toBe(200)151+ expect(await res.text()).toBe('post /book')152+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)160+ expect(await res.text()).toBe('get /user/login')161+162+ req = new Request('http://localhost/user/regist', { method: 'POST' })163+ res = await app.dispatch(req)164+ expect(res.status).toBe(200)165+ expect(await res.text()).toBe('post /user/regist')166+ })167+})168+169+describe('param and query', () => {170+ const app = new Hono()171+172+ app.get('/entry/:id', (c) => {173+ const id = c.req.param('id')174+ return new Response(`id is ${id}`, {175+ status: 200,176+ })177+ })178+179+ app.get('/search', (c) => {180+ const name = c.req.query('name')181+ return new Response(`name is ${name}`, {182+ status: 200,183+ })184+ })185+186+ app.get('/add-header', (c) => {187+ const bar = c.req.header('X-Foo')188+ return new Response(`foo is ${bar}`, {189+ status: 200,190+ })191+ })192+193+ it('param of /entry/:id is found', async () => {194+ const req = new Request('http://localhost/entry/123')195+ const res = await app.dispatch(req)196+ expect(res.status).toBe(200)197+ expect(await res.text()).toBe('id is 123')198+ })199+200+ it('query of /search?name=sam is found', async () => {201+ const req = new Request('http://localhost/search?name=sam')202+ const res = await app.dispatch(req)203+ expect(res.status).toBe(200)204+ expect(await res.text()).toBe('name is sam')205+ })206+207+ it('/add-header header - X-Foo is Bar', async () => {208+ const req = new Request('http://localhost/add-header')209+ req.headers.append('X-Foo', 'Bar')210+ const res = await app.dispatch(req)211+ expect(res.status).toBe(200)212+ expect(await res.text()).toBe('foo is Bar')213+ })214+})215+216+describe('Middleware', () => {217+ const app = new Hono()218+219+ // Custom Logger220+ app.use('*', async (c, next) => {221+ console.log(`${c.req.method} : ${c.req.url}`)222+ await next()223+ })224+225+ // Apeend Custom Header226+ app.use('*', async (c, next) => {227+ await next()228+ c.res.headers.append('x-custom', 'root')229+ })230+231+ app.use('/hello', async (c, next) => {232+ await next()233+ c.res.headers.append('x-message', 'custom-header')234+ })235+236+ app.use('/hello/*', async (c, next) => {237+ await next()238+ c.res.headers.append('x-message-2', 'custom-header-2')239+ })240+241+ app.get('/hello', () => {242+ return new Response('hello')243+ })244+ app.get('/hello/:message', (c) => {245+ const message = c.req.param('message')246+ return new Response(`${message}`)247+ })248+249+ it('logging and custom header', async () => {250+ const req = new Request('http://localhost/hello')251+ const res = await app.dispatch(req)252+ expect(res.status).toBe(200)253+ expect(await res.text()).toBe('hello')254+ expect(res.headers.get('x-custom')).toBe('root')255+ expect(res.headers.get('x-message')).toBe('custom-header')256+ expect(res.headers.get('x-message-2')).toBe('custom-header-2')257+ })258+259+ it('logging and custom header with named param', async () => {260+ const req = new Request('http://localhost/hello/message')261+ const res = await app.dispatch(req)262+ expect(res.status).toBe(200)263+ expect(await res.text()).toBe('message')264+ expect(res.headers.get('x-custom')).toBe('root')265+ expect(res.headers.get('x-message-2')).toBe('custom-header-2')266+ })267+})268+269+describe('404 Not Found', () => {270+ const app = new Hono()271+272+ app.notFound = (c) => {273+ return c.text('Custom 404 Not Found', 404)274+ }275+276+ app.get('/hello', (c) => {277+ return c.text('hello')278+ })279+280+ app.get('/notfound', (c) => {281+ return c.notFound()282+ })283+284+ it('Custom 404 Not Found', async () => {285+ let req = new Request('http://localhost/hello')286+ let res = await app.dispatch(req)287+ expect(res.status).toBe(200)288+ req = new Request('http://localhost/notfound')289+ res = await app.dispatch(req)290+ expect(res.status).toBe(404)291+ req = new Request('http://localhost/foo')292+ res = await app.dispatch(req)293+ expect(res.status).toBe(404)294+ expect(await res.text()).toBe('Custom 404 Not Found')295+ })296+})297+298+describe('Redirect', () => {299+ const app = new Hono()300+ app.get('/redirect', (c) => {301+ return c.redirect('/')302+ })303+304+ it('Absolute URL', async () => {305+ const req = new Request('https://example.com/redirect')306+ const res = await app.dispatch(req)307+ expect(res.status).toBe(302)308+ expect(res.headers.get('Location')).toBe('https://example.com/')309+ })310+})311+312+describe('Error handle', () => {313+ const app = new Hono()314+315+ app.get('/error', () => {316+ throw new Error('This is Error')317+ })318+319+ app.use('/error-middleware', async () => {320+ throw new Error('This is Middleware Error')321+ })322+323+ app.onError = (err, c) => {324+ c.header('debug', err.message)325+ return c.text('Custom Error Message', 500)326+ }327+328+ it('Custom Error Message', async () => {329+ let req = new Request('https://example.com/error')330+ let res = await app.dispatch(req)331+ expect(res.status).toBe(500)332+ expect(await res.text()).toBe('Custom Error Message')333+ expect(res.headers.get('debug')).toBe('This is Error')334+335+ req = new Request('https://example.com/error-middleware')336+ res = await app.dispatch(req)337+ expect(res.status).toBe(500)338+ expect(await res.text()).toBe('Custom Error Message')339+ expect(res.headers.get('debug')).toBe('This is Middleware Error')340+ })341+})342+343+describe('Request methods with custom middleware', () => {344+ const app = new Hono()345+346+ app.use('*', async (c, next) => {347+ const query = c.req.query('foo')348+ const param = c.req.param('foo')349+ const header = c.req.header('User-Agent')350+ await next()351+ c.header('X-Query-2', query)352+ c.header('X-Param-2', param)353+ c.header('X-Header-2', header)354+ })355+356+ app.get('/:foo', (c) => {357+ const query = c.req.query('foo')358+ const param = c.req.param('foo')359+ const header = c.req.header('User-Agent')360+ c.header('X-Query', query)361+ c.header('X-Param', param)362+ c.header('X-Header', header)363+ return c.body('Hono')364+ })365+366+ it('query', async () => {367+ const url = new URL('http://localhost/bar')368+ url.searchParams.append('foo', 'bar')369+ const req = new Request(url.toString())370+ req.headers.append('User-Agent', 'bar')371+ const res = await app.dispatch(req)372+373+ expect(res.status).toBe(200)374+ expect(res.headers.get('X-Query')).toBe('bar')375+ expect(res.headers.get('X-Param')).toBe('bar')376+ expect(res.headers.get('X-Header')).toBe('bar')377+378+ expect(res.headers.get('X-Query-2')).toBe('bar')379+ expect(res.headers.get('X-Param-2')).toBe('bar')380+ expect(res.headers.get('X-Header-2')).toBe('bar')381+ })382+})modified:src/hono.ts+3 added-20 removed
1-import { Node } from './node'1 import { compose } from './compose'2 import { getPathFromURL, mergePath } from './utils/url'3 import { Context } from './context'4 import type { Env } from './context'6-import type { Result } from './router'7-import { Router, METHOD_NAME_OF_ALL } from './router'5+import type { Result, Router } from './router'6+import { METHOD_NAME_OF_ALL } from './router'7+import { TrieRouter } from './router/trie-router' // Default Router8 9 declare global {10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string22 unmodified lines34 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`35 ? ParamKey<Component> | ParamKeys<Rest>36 : ParamKey<Path>37 38-export class TrieRouter<T> extends Router<T> {39- node: Node<T>40-41- constructor() {42- super()43- this.node = new Node()44- }45-46- add(method: string, path: string, handler: T) {47- this.node.insert(method, path, handler)48- }49-50- match(method: string, path: string): Result<T> | null {51- return this.node.search(method, path)52- }53-}54-38 export class Hono {39 routerClass: { new (): Router<any> } = TrieRouter40 strict: boolean = true // strict routing - default is true41 router: Router<Handler>161 unmodified linesdeleted:src/node.ts-120 removed
1-import type { Pattern } from './utils/url'2-import { splitPath, getPattern } from './utils/url'3-import { Result, METHOD_NAME_OF_ALL } from './router'4-5-const noRoute = (): null => {6- return null7-}8-9-export class Node<T> {10- method: Record<string, T>11- handler: T12- children: Record<string, Node<T>>13- middlewares: []14- patterns: Pattern[]15-16- constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {17- this.children = children || {}18- this.method = {}19- if (method && handler) {20- this.method[method] = handler21- }22- this.middlewares = []23- this.patterns = []24- }25-26- insert(method: string, path: string, handler: T): Node<T> {27- // eslint-disable-next-line @typescript-eslint/no-this-alias28- let curNode: Node<T> = this29- const parts = splitPath(path)30- for (let i = 0, len = parts.length; i < len; i++) {31- const p: string = parts[i]32- if (Object.keys(curNode.children).includes(p)) {33- curNode = curNode.children[p]34- continue35- }36- curNode.children[p] = new Node()37- const pattern = getPattern(p)38- if (pattern) {39- curNode.patterns.push(pattern)40- }41-42- curNode = curNode.children[p]43- }44- curNode.method[method] = handler45- return curNode46- }47-48- search(method: string, path: string): Result<T> {49- // eslint-disable-next-line @typescript-eslint/no-this-alias50- let curNode: Node<T> = this51-52- const params: { [key: string]: string } = {}53- const parts = splitPath(path)54-55- for (let i = 0, len = parts.length; i < len; i++) {56- const p: string = parts[i]57-58- // '*' => match any path59- // /api/* => default wildcard match60- if (curNode.children['*'] && !curNode.children[p]) {61- const astNode = curNode.children['*']62- if (Object.keys(astNode.children).length === 0) {63- curNode = astNode64- break65- }66- }67-68- const nextNode = curNode.children[p]69-70- if (nextNode) {71- curNode = nextNode72- // '/hello/*' => match '/hello'73- if (!(i == len - 1 && nextNode.children['*'])) {74- continue75- }76- }77-78- let isWildcard = false79- let isParamMatch = false80-81- for (let j = 0, len = curNode.patterns.length; j < len; j++) {82- const pattern = curNode.patterns[j]83-84- // Wildcard85- // '/hello/*/foo' => match /hello/bar/foo86- if (pattern === '*') {87- curNode = curNode.children['*']88- isWildcard = true89- break90- }91-92- // Named match93- const [key, name, matcher] = pattern94- if (p !== '' && (matcher === true || matcher.test(p))) {95- params[name] = p96- curNode = curNode.children[key]97- isParamMatch = true98- break99- }100- return noRoute()101- }102-103- if (isWildcard && i === len - 1) {104- break105- }106-107- if (isWildcard === false && isParamMatch === false) {108- return noRoute()109- }110- }111-112- const handler = curNode.method[METHOD_NAME_OF_ALL] || curNode.method[method]113-114- if (!handler) {115- return noRoute()116- }117-118- return new Result<T>(handler, params)119- }120-}deleted:test/compose.test.ts-47 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import { compose } from '../src/compose'
type C = { req: { [key: string]: string } res: { [key: string]: string }}
describe('compose middleware', () => { const middleware: Function[] = []
const a = async (c: C, next: Function) => { c.req['log'] = 'log' await next() } middleware.push(a)
const b = async (c: C, next: Function) => { await next() c.res['headers'] = `${c.res.headers}-custom-header` } middleware.push(b)
const handler = async (c: C, next: Function) => { c.req['log'] = `${c.req.log} message` await next() c.res = { message: 'new response' } } middleware.push(handler)
const request = {} const response = {}
it('Request', async () => { const c: C = { req: request, res: response } const composed = compose<C>(middleware) await composed(c) expect(c.req['log']).not.toBeNull() expect(c.req['log']).toBe('log message') }) it('Response', async () => { const c: C = { req: request, res: response } const composed = compose(middleware) await composed(c) expect(c.res['header']).not.toBeNull() expect(c.res['message']).toBe('new response') })})deleted:test/context.test.ts-98 removed
1-import { Context } from '../src/context'2-3-describe('Context', () => {4- const req = new Request('http://localhost/')5- const c = new Context(req)6-7- it('c.text()', async () => {8- const res = c.text('text in c', 201, { 'X-Custom': 'Message' })9- expect(res.status).toBe(201)10- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=UTF-8')11- expect(await res.text()).toBe('text in c')12- expect(res.headers.get('X-Custom')).toBe('Message')13- })14-15- it('c.json()', async () => {16- const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })17- expect(res.status).toBe(201)18- expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')19- const text = await res.text()20- const object = JSON.parse(text)21- expect(object.message).toBe('Hello')22- expect(res.headers.get('X-Custom')).toBe('Message')23- })24-25- it('c.html()', async () => {26- const res = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })27- expect(res.status).toBe(201)28- expect(res.headers.get('Content-Type')).toMatch('text/html')29- expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')30- expect(res.headers.get('X-Custom')).toBe('Message')31- })32-33- it('c.redirect()', async () => {34- let res = c.redirect('/destination')35- expect(res.status).toBe(302)36- expect(res.headers.get('Location')).toMatch(/^https?:\/\/.+\/destination$/)37- res = c.redirect('https://example.com/destination')38- expect(res.status).toBe(302)39- expect(res.headers.get('Location')).toBe('https://example.com/destination')40- })41-42- it('c.header()', async () => {43- c.header('X-Foo', 'Bar')44- const res = c.body('Hi')45- const foo = res.headers.get('X-Foo')46- expect(foo).toBe('Bar')47- })48-49- it('c.status() and c.statusText()', async () => {50- c.status(201)51- const res = c.body('Hi')52- expect(res.status).toBe(201)53- expect(res.statusText).toBe('Created')54- })55-56- it('Complext pattern', async () => {57- c.status(404)58- const res = c.json({ hono: 'great app' })59- expect(res.status).toBe(404)60- expect(res.statusText).toBe('Not Found')61- expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')62- const obj: { [key: string]: string } = await res.json()63- expect(obj['hono']).toBe('great app')64- })65-66- it('Content-Length', async () => {67- let res = c.text('abcdefg')68- expect(res.headers.get('Content-Length')).toBe('7')69- res = c.text('炎')70- expect(res.headers.get('Content-Length')).toBe('3')71- })72-73- it('Headers, status, statusText', async () => {74- c.header('X-Custom1', 'Message1')75- c.header('X-Custom2', 'Message2')76- c.status(200)77- const res = c.newResponse('this is body', {78- status: 201,79- headers: {80- 'X-Custom3': 'Message3',81- 'X-Custom2': 'Message2-Override',82- },83- })84- expect(res.headers.get('X-Custom1')).toBe('Message1')85- expect(res.headers.get('X-Custom2')).toBe('Message2-Override')86- expect(res.headers.get('X-Custom3')).toBe('Message3')87- expect(res.status).toBe(201)88- expect(await res.text()).toBe('this is body')89-90- // res is already setted.91- c.res = res92- c.header('X-Custom4', 'Message4')93- c.status(202)94- expect(c.res.headers.get('X-Custom4')).toBe('Message4')95- expect(c.res.status).toBe(201)96- expect(c.res.statusText).toBe('OK')97- })98-})deleted:test/hono.test.ts-382 removed
1-import { Hono } from '../src/index'2-3-describe('GET Request', () => {4- const app = new Hono()5-6- app.get('/hello', () => {7- return new Response('hello', {8- status: 200,9- statusText: 'Hono is OK',10- })11- })12-13- app.get('/hello-with-shortcuts', (c) => {14- c.header('X-Custom', 'This is Hono')15- c.status(201)16- return c.html('<h1>Hono!!!</h1>')17- })18-19- app.notFound = () => {20- return new Response('not found', {21- status: 404,22- })23- }24-25- it('GET /hello is ok', async () => {26- const req = new Request('http://localhost/hello')27- const res = await app.dispatch(req)28- expect(res).not.toBeNull()29- expect(res.status).toBe(200)30- expect(res.statusText).toBe('Hono is OK')31- expect(await res.text()).toBe('hello')32- })33-34- it('GET /hell-with-shortcuts is ok', async () => {35- const req = new Request('http://localhost/hello-with-shortcuts')36- const res = await app.dispatch(req)37- expect(res).not.toBeNull()38- expect(res.status).toBe(201)39- expect(res.statusText).toBe('Created')40- expect(res.headers.get('X-Custom')).toBe('This is Hono')41- expect(res.headers.get('Content-Type')).toMatch(/text\/html/)42- expect(await res.text()).toBe('<h1>Hono!!!</h1>')43- })44-45- it('GET / is not found', async () => {46- const req = new Request('http://localhost/')47- const res = await app.dispatch(req)48- expect(res).not.toBeNull()49- expect(res.status).toBe(404)50- })51-})52-53-describe('strict parameter', () => {54- describe('strict is true with not slash', () => {55- const app = new Hono()56-57- app.get('/hello', (c) => {58- return c.text('/hello')59- })60-61- it('/hello/ is not found', async () => {62- let req = new Request('http://localhost/hello')63- let res = await app.dispatch(req)64- expect(res).not.toBeNull()65- expect(res.status).toBe(200)66- req = new Request('http://localhost/hello/')67- res = await app.dispatch(req)68- expect(res).not.toBeNull()69- expect(res.status).toBe(404)70- })71- })72-73- describe('strict is true with slash', () => {74- const app = new Hono()75-76- app.get('/hello/', (c) => {77- return c.text('/hello/')78- })79-80- it('/hello is not found', async () => {81- let req = new Request('http://localhost/hello/')82- let res = await app.dispatch(req)83- expect(res).not.toBeNull()84- expect(res.status).toBe(200)85- req = new Request('http://localhost/hello')86- res = await app.dispatch(req)87- expect(res).not.toBeNull()88- expect(res.status).toBe(404)89- })90- })91-92- describe('strict is false', () => {93- const app = new Hono({ strict: false })94-95- app.get('/hello', (c) => {96- return c.text('/hello')97- })98-99- it('/hello and /hello/ are treated as the same', async () => {100- let req = new Request('http://localhost/hello')101- let res = await app.dispatch(req)102- expect(res).not.toBeNull()103- expect(res.status).toBe(200)104- req = new Request('http://localhost/hello/')105- res = await app.dispatch(req)106- expect(res).not.toBeNull()107- expect(res.status).toBe(200)108- })109- })110-})111-112-describe('Routing', () => {113- const app = new Hono()114-115- it('Return it self', async () => {116- const appRes = app.get('/', () => new Response('get /'))117- expect(appRes).not.toBeUndefined()118- appRes.delete('/', () => new Response('delete /'))119- const req = new Request('http://localhost/', { method: 'DELETE' })120- const res = await appRes.dispatch(req)121- expect(res).not.toBeNull()122- expect(res.status).toBe(200)123- expect(await res.text()).toBe('delete /')124- })125-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)141- expect(await res.text()).toBe('get /book')142-143- req = new Request('http://localhost/book/123', { method: 'GET' })144- res = await app.dispatch(req)145- expect(res.status).toBe(200)146- expect(await res.text()).toBe('get /book/123')147-148- req = new Request('http://localhost/book', { method: 'POST' })149- res = await app.dispatch(req)150- expect(res.status).toBe(200)151- expect(await res.text()).toBe('post /book')152-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)160- expect(await res.text()).toBe('get /user/login')161-162- req = new Request('http://localhost/user/regist', { method: 'POST' })163- res = await app.dispatch(req)164- expect(res.status).toBe(200)165- expect(await res.text()).toBe('post /user/regist')166- })167-})168-169-describe('param and query', () => {170- const app = new Hono()171-172- app.get('/entry/:id', (c) => {173- const id = c.req.param('id')174- return new Response(`id is ${id}`, {175- status: 200,176- })177- })178-179- app.get('/search', (c) => {180- const name = c.req.query('name')181- return new Response(`name is ${name}`, {182- status: 200,183- })184- })185-186- app.get('/add-header', (c) => {187- const bar = c.req.header('X-Foo')188- return new Response(`foo is ${bar}`, {189- status: 200,190- })191- })192-193- it('param of /entry/:id is found', async () => {194- const req = new Request('http://localhost/entry/123')195- const res = await app.dispatch(req)196- expect(res.status).toBe(200)197- expect(await res.text()).toBe('id is 123')198- })199-200- it('query of /search?name=sam is found', async () => {201- const req = new Request('http://localhost/search?name=sam')202- const res = await app.dispatch(req)203- expect(res.status).toBe(200)204- expect(await res.text()).toBe('name is sam')205- })206-207- it('/add-header header - X-Foo is Bar', async () => {208- const req = new Request('http://localhost/add-header')209- req.headers.append('X-Foo', 'Bar')210- const res = await app.dispatch(req)211- expect(res.status).toBe(200)212- expect(await res.text()).toBe('foo is Bar')213- })214-})215-216-describe('Middleware', () => {217- const app = new Hono()218-219- // Custom Logger220- app.use('*', async (c, next) => {221- console.log(`${c.req.method} : ${c.req.url}`)222- await next()223- })224-225- // Apeend Custom Header226- app.use('*', async (c, next) => {227- await next()228- c.res.headers.append('x-custom', 'root')229- })230-231- app.use('/hello', async (c, next) => {232- await next()233- c.res.headers.append('x-message', 'custom-header')234- })235-236- app.use('/hello/*', async (c, next) => {237- await next()238- c.res.headers.append('x-message-2', 'custom-header-2')239- })240-241- app.get('/hello', () => {242- return new Response('hello')243- })244- app.get('/hello/:message', (c) => {245- const message = c.req.param('message')246- return new Response(`${message}`)247- })248-249- it('logging and custom header', async () => {250- const req = new Request('http://localhost/hello')251- const res = await app.dispatch(req)252- expect(res.status).toBe(200)253- expect(await res.text()).toBe('hello')254- expect(res.headers.get('x-custom')).toBe('root')255- expect(res.headers.get('x-message')).toBe('custom-header')256- expect(res.headers.get('x-message-2')).toBe('custom-header-2')257- })258-259- it('logging and custom header with named param', async () => {260- const req = new Request('http://localhost/hello/message')261- const res = await app.dispatch(req)262- expect(res.status).toBe(200)263- expect(await res.text()).toBe('message')264- expect(res.headers.get('x-custom')).toBe('root')265- expect(res.headers.get('x-message-2')).toBe('custom-header-2')266- })267-})268-269-describe('404 Not Found', () => {270- const app = new Hono()271-272- app.notFound = (c) => {273- return c.text('Custom 404 Not Found', 404)274- }275-276- app.get('/hello', (c) => {277- return c.text('hello')278- })279-280- app.get('/notfound', (c) => {281- return c.notFound()282- })283-284- it('Custom 404 Not Found', async () => {285- let req = new Request('http://localhost/hello')286- let res = await app.dispatch(req)287- expect(res.status).toBe(200)288- req = new Request('http://localhost/notfound')289- res = await app.dispatch(req)290- expect(res.status).toBe(404)291- req = new Request('http://localhost/foo')292- res = await app.dispatch(req)293- expect(res.status).toBe(404)294- expect(await res.text()).toBe('Custom 404 Not Found')295- })296-})297-298-describe('Redirect', () => {299- const app = new Hono()300- app.get('/redirect', (c) => {301- return c.redirect('/')302- })303-304- it('Absolute URL', async () => {305- const req = new Request('https://example.com/redirect')306- const res = await app.dispatch(req)307- expect(res.status).toBe(302)308- expect(res.headers.get('Location')).toBe('https://example.com/')309- })310-})311-312-describe('Error handle', () => {313- const app = new Hono()314-315- app.get('/error', () => {316- throw new Error('This is Error')317- })318-319- app.use('/error-middleware', async () => {320- throw new Error('This is Middleware Error')321- })322-323- app.onError = (err, c) => {324- c.header('debug', err.message)325- return c.text('Custom Error Message', 500)326- }327-328- it('Custom Error Message', async () => {329- let req = new Request('https://example.com/error')330- let res = await app.dispatch(req)331- expect(res.status).toBe(500)332- expect(await res.text()).toBe('Custom Error Message')333- expect(res.headers.get('debug')).toBe('This is Error')334-335- req = new Request('https://example.com/error-middleware')336- res = await app.dispatch(req)337- expect(res.status).toBe(500)338- expect(await res.text()).toBe('Custom Error Message')339- expect(res.headers.get('debug')).toBe('This is Middleware Error')340- })341-})342-343-describe('Request methods with custom middleware', () => {344- const app = new Hono()345-346- app.use('*', async (c, next) => {347- const query = c.req.query('foo')348- const param = c.req.param('foo')349- const header = c.req.header('User-Agent')350- await next()351- c.header('X-Query-2', query)352- c.header('X-Param-2', param)353- c.header('X-Header-2', header)354- })355-356- app.get('/:foo', (c) => {357- const query = c.req.query('foo')358- const param = c.req.param('foo')359- const header = c.req.header('User-Agent')360- c.header('X-Query', query)361- c.header('X-Param', param)362- c.header('X-Header', header)363- return c.body('Hono')364- })365-366- it('query', async () => {367- const url = new URL('http://localhost/bar')368- url.searchParams.append('foo', 'bar')369- const req = new Request(url.toString())370- req.headers.append('User-Agent', 'bar')371- const res = await app.dispatch(req)372-373- expect(res.status).toBe(200)374- expect(res.headers.get('X-Query')).toBe('bar')375- expect(res.headers.get('X-Param')).toBe('bar')376- expect(res.headers.get('X-Header')).toBe('bar')377-378- expect(res.headers.get('X-Query-2')).toBe('bar')379- expect(res.headers.get('X-Param-2')).toBe('bar')380- expect(res.headers.get('X-Header-2')).toBe('bar')381- })382-})deleted:test/node.test.ts-193 removed
1-import { Node } from '../src/node'2-3-describe('Root Node', () => {4- const node = new Node()5- node.insert('get', '/', 'get root')6- it('get /', () => {7- const res = node.search('get', '/')8- expect(res).not.toBeNull()9- expect(res.handler).toBe('get root')10- expect(node.search('get', '/hello')).toBeNull()11- })12-})13-14-describe('Root Node is not defined', () => {15- const node = new Node()16- node.insert('get', '/hello', 'get hello')17- it('get /', () => {18- expect(node.search('get', '/')).toBeNull()19- })20-})21-22-describe('All with *', () => {23- const node = new Node()24- node.insert('get', '*', 'get all')25- it('get /', () => {26- expect(node.search('get', '/')).not.toBeNull()27- expect(node.search('get', '/hello')).not.toBeNull()28- })29-})30-31-describe('Basic Usage', () => {32- const node = new Node()33- node.insert('get', '/hello', 'get hello')34- node.insert('post', '/hello', 'post hello')35- node.insert('get', '/hello/foo', 'get hello foo')36-37- it('get, post /hello', () => {38- expect(node.search('get', '/')).toBeNull()39- expect(node.search('post', '/')).toBeNull()40-41- expect(node.search('get', '/hello').handler).toBe('get hello')42- expect(node.search('post', '/hello').handler).toBe('post hello')43- expect(node.search('put', '/hello')).toBeNull()44- })45- it('get /nothing', () => {46- expect(node.search('get', '/nothing')).toBeNull()47- })48- it('/hello/foo, /hello/bar', () => {49- expect(node.search('get', '/hello/foo').handler).toBe('get hello foo')50- expect(node.search('post', '/hello/foo')).toBeNull()51- expect(node.search('get', '/hello/bar')).toBeNull()52- })53- it('/hello/foo/bar', () => {54- expect(node.search('get', '/hello/foo/bar')).toBeNull()55- })56-})57-58-describe('Name path', () => {59- const node = new Node()60- node.insert('get', '/entry/:id', 'get entry')61- node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')62- node.insert('get', '/map/:location/events', 'get events')63-64- it('get /entry/123', () => {65- const res = node.search('get', '/entry/123')66- expect(res).not.toBeNull()67- expect(res.handler).toBe('get entry')68- expect(res.params).not.toBeNull()69- expect(res.params['id']).toBe('123')70- expect(res.params['id']).not.toBe('1234')71- })72-73- it('get /entry/456/comment', () => {74- const res = node.search('get', '/entry/456/comment')75- expect(res).toBeNull()76- })77-78- it('get /entry/789/comment/123', () => {79- const res = node.search('get', '/entry/789/comment/123')80- expect(res).not.toBeNull()81- expect(res.handler).toBe('get comment')82- expect(res.params['id']).toBe('789')83- expect(res.params['comment_id']).toBe('123')84- })85-86- it('get /map/:location/events', () => {87- const res = node.search('get', '/map/yokohama/events')88- expect(res).not.toBeNull()89- expect(res.handler).toBe('get events')90- expect(res.params['location']).toBe('yokohama')91- })92-})93-94-describe('Wildcard', () => {95- const node = new Node()96- node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')97- it('/wildcard-abc/xxxxxx/wildcard-efg', () => {98- const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')99- expect(res).not.toBeNull()100- expect(res.handler).toBe('wildcard')101- })102- node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard')103- it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => {104- const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk')105- expect(res).not.toBeNull()106- expect(res.handler).toBe('wildcard')107- })108-})109-110-describe('Regexp', () => {111- const node = new Node()112- node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')113- it('/regexp-abc/123/comment/abc', () => {114- const res = node.search('get', '/regex-abc/123/comment/abc')115- expect(res).not.toBeNull()116- expect(res.handler).toBe('regexp')117- expect(res.params['id']).toBe('123')118- expect(res.params['comment_id']).toBe('abc')119- })120- it('/regexp-abc/abc', () => {121- const res = node.search('get', '/regex-abc/abc')122- expect(res).toBeNull()123- })124- it('/regexp-abc/123/comment/123', () => {125- const res = node.search('get', '/regex-abc/123/comment/123')126- expect(res).toBeNull()127- })128-})129-130-describe('All', () => {131- const node = new Node()132- node.insert('ALL', '/all-methods', 'all methods') // ALL133- it('/all-methods', () => {134- let res = node.search('get', '/all-methods')135- expect(res).not.toBeNull()136- expect(res.handler).toBe('all methods')137- res = node.search('put', '/all-methods')138- expect(res).not.toBeNull()139- expect(res.handler).toBe('all methods')140- })141-})142-143-describe('Special Wildcard', () => {144- const node = new Node()145- node.insert('ALL', '*', 'match all')146-147- it('/foo', () => {148- const res = node.search('get', '/foo')149- expect(res).not.toBeNull()150- expect(res.handler).toBe('match all')151- })152- it('/hello', () => {153- const res = node.search('get', '/hello')154- expect(res).not.toBeNull()155- expect(res.handler).toBe('match all')156- })157- it('/hello/foo', () => {158- const res = node.search('get', '/hello/foo')159- expect(res).not.toBeNull()160- expect(res.handler).toBe('match all')161- })162-})163-164-describe('Special Wildcard deeply', () => {165- const node = new Node()166- node.insert('ALL', '/hello/*', 'match hello')167- it('/hello', () => {168- const res = node.search('get', '/hello')169- expect(res).not.toBeNull()170- expect(res.handler).toBe('match hello')171- })172- it('/hello/foo', () => {173- const res = node.search('get', '/hello/foo')174- expect(res).not.toBeNull()175- expect(res.handler).toBe('match hello')176- })177-})178-179-describe('Default with wildcard', () => {180- const node = new Node()181- node.insert('ALL', '/api/abc', 'match api')182- node.insert('ALL', '/api/*', 'fallback')183- it('/api/abc', () => {184- const res = node.search('get', '/api/abc')185- expect(res).not.toBeNull()186- expect(res.handler).toBe('match api')187- })188- it('/api/def', () => {189- const res = node.search('get', '/api/def')190- expect(res).not.toBeNull()191- expect(res.handler).toBe('fallback')192- })193-})deleted:test/router.test.ts-67 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { TrieRouter } from '../src/hono'
describe('Basic Usage', () => { const router = new TrieRouter<string>()
router.add('GET', '/hello', 'get hello') router.add('POST', '/hello', 'post hello')
it('get, post hello', async () => { let res = router.match('GET', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get hello')
res = router.match('POST', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('post hello')
res = router.match('PUT', '/hello') expect(res).toBeNull()
res = router.match('GET', '/') expect(res).toBeNull() })})
describe('Complex', () => { const router = new TrieRouter<string>()
it('Named Param', async () => { router.add('GET', '/entry/:id', 'get entry') const res = router.match('GET', '/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('get entry') expect(res.params['id']).toBe('123') })
it('Wildcard', async () => { router.add('GET', '/wild/*/card', 'get wildcard') const res = router.match('GET', '/wild/xxx/card') expect(res).not.toBeNull() expect(res.handler).toBe('get wildcard') })
it('Default', async () => { router.add('GET', '/api/abc', 'get api') router.add('GET', '/api/*', 'fallback') let res = router.match('GET', '/api/abc') expect(res).not.toBeNull() expect(res.handler).toBe('get api') res = router.match('GET', '/api/def') expect(res).not.toBeNull() expect(res.handler).toBe('fallback') })
it('Regexp', async () => { router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post') let res = router.match('GET', '/post/20210101/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get post') expect(res.params['date']).toBe('20210101') expect(res.params['title']).toBe('hello') res = router.match('GET', '/post/onetwothree') expect(res).toBeNull() res = router.match('GET', '/post/123/123') expect(res).toBeNull() })})modified:package.json+1 added-1 removed
48 unmodified lines49 }50 },51 "scripts": {52 "test": "jest",53- "lint": "eslint --ext js,ts src .eslintrc.js test && prettier --check src",53+ "lint": "eslint --ext js,ts src .eslintrc.js && prettier --check src",54 "build": "rimraf dist && tsc",55 "watch": "tsc -w",56 "prepublishOnly": "yarn build"57 },47 unmodified lines