Update router!
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by Yusuke Wada · parent 5777f2c · Browse files · 6 files·+319 added−239 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+319 added−239 removed
- tests:+170 added−73 removed
- other:+149 added−166 removed
Provenance
- Commit
8ccbd61- Tree
69ded13- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent
5777f2c
6 files changed+319 added−239 removed
modified:example/basic/index.js+1 added-37 removed
12124567891011121314151617181920212223242526272829303132333435363738const Hono = require('../../src/hono')const app = Hono()const window = this;
// Textapp.get('/', () => 'Hono!!')
// JSONapp.get('/api', () => { return { message: 'Hello! from /api' } })
app.get('/entry', () => 'Get entry')app.post('/entry', () => 'Post entry')
//app.route('/book')// .get(() => 'Get a random book')// .post(() => 'Add a book')// .put(() => 'Update a book')
// With original response headerapp.get('/hello', () => { return new Response('Hello! from /hello', { status: 200, headers: { 'X-Message': 'This is Hono' } })})
const notFound = () => { return new Response('not found', { status: 404 })}
app.get('/not_found', (req) => { notFound()})
app.fire()No newline at end of fileadded:src/node.js+119 added
1+const methodNameOfAll = 'all'2+3+class Result {4+ constructor({ handler, params } = {}) {5+ this.handler = handler6+ this.params = params || {}7+ }8+}9+10+class Node {11+ constructor({ method, label, handler, children } = {}) {12+ this.label = label || '/'13+ this.children = children || []14+ this.method = {}15+ if (method && handler) {16+ this.method[method] = handler17+ }18+ }19+20+ insert(method, path, handler) {21+ let curNode = this22+ const ps = this.splitPath(path)23+ for (const p of ps) {24+ let nextNode = curNode.children[p]25+ if (nextNode) {26+ curNode = nextNode27+ } else {28+ curNode.children[p] = new Node({29+ method: method,30+ label: p,31+ handler: handler,32+ })33+ curNode = curNode.children[p]34+ }35+ }36+ // XXX37+ if (!curNode.method[method]) {38+ curNode.method[method] = handler39+ }40+ }41+42+ splitPath(path) {43+ let ps = ['/']44+ for (const p of path.split('/')) {45+ if (p) {46+ ps.push(p)47+ }48+ }49+ return ps50+ }51+52+ getPattern(label) {53+ // :id{[0-9]+} → [0-9]+$54+ // :id → (.+)55+ const match = label.match(/^\:.+?\{(.+)\}$/)56+ if (match) {57+ return '(' + match[1] + ')'58+ }59+ return '(.+)'60+ }61+62+ getParamName(label) {63+ const match = label.match(/^\:([^\{\}]+)/)64+ if (match) {65+ return match[1]66+ }67+ }68+69+ search(method, path) {70+ let curNode = this71+ const params = {}72+ for (const p of this.splitPath(path)) {73+ let nextNode = curNode.children[p]74+ if (nextNode) {75+ curNode = nextNode76+ continue77+ }78+ let isParamMatch = false79+ for (const key in curNode.children) {80+ if (key === '*') {81+ // Wildcard82+ curNode = curNode.children[key]83+ isParamMatch = true84+ break85+ }86+ if (key.match(/^:/)) {87+ const pattern = this.getPattern(key)88+ const match = p.match(new RegExp(pattern))89+ if (match) {90+ const k = this.getParamName(key)91+ params[k] = match[0]92+ curNode = curNode.children[key]93+ isParamMatch = true94+ break95+ }96+ return this.noRoute()97+ }98+ }99+ if (isParamMatch == false) {100+ return this.noRoute()101+ }102+ }103+104+ let handler = curNode.method[methodNameOfAll] || curNode.method[method]105+106+ if (handler) {107+ const res = new Result({ handler: handler, params: params })108+ return res109+ } else {110+ return this.noRoute()111+ }112+ }113+114+ noRoute() {115+ return null116+ }117+}118+119+module.exports = Nodeadded:src/node.test.js+110 added
1+const Node = require('./node')2+const node = new Node()3+4+describe('Util Methods', () => {5+ it('node.splitPath', () => {6+ let ps = node.splitPath('/')7+ expect(ps[0]).toBe('/')8+ ps = node.splitPath('/hello')9+ expect(ps[0]).toBe('/')10+ expect(ps[1]).toBe('hello')11+ })12+})13+14+describe('Basic Usage', () => {15+ node.insert('get', '/', 'get root')16+ node.insert('get', '/hello', 'get hello')17+ node.insert('post', '/hello', 'post hello')18+ node.insert('get', '/hello/foo', 'get hello foo')19+20+ it('get, post /hello', () => {21+ expect(node.search('get', '/').handler).toBe('get root')22+ expect(node.search('post', '/')).toBeNull()23+24+ expect(node.search('get', '/hello').handler).toBe('get hello')25+ expect(node.search('post', '/hello').handler).toBe('post hello')26+ expect(node.search('put', '/hello')).toBeNull()27+ })28+ it('get /nothing', () => {29+ expect(node.search('get', '/nothing')).toBeNull()30+ })31+ it('/hello/foo, /hello/bar', () => {32+ expect(node.search('get', '/hello/foo').handler).toBe('get hello foo')33+ expect(node.search('post', '/hello/foo')).toBeNull()34+ expect(node.search('get', '/hello/bar')).toBeNull()35+ })36+ it('/hello/foo/bar', () => {37+ expect(node.search('get', '/hello/foo/bar')).toBeNull()38+ })39+})40+41+describe('Name path', () => {42+ it('get /entry/123', () => {43+ node.insert('get', '/entry/:id', 'get entry')44+ let res = node.search('get', '/entry/123')45+ expect(res).not.toBeNull()46+ expect(res.handler).toBe('get entry')47+ expect(res.params).not.toBeNull()48+ expect(res.params['id']).toBe('123')49+ expect(res.params['id']).not.toBe('1234')50+ })51+52+ it('get /entry/456/comment', () => {53+ node.insert('get', '/entry/:id', 'get entry')54+ res = node.search('get', '/entry/456/comment')55+ expect(res).toBeNull()56+ })57+58+ it('get /entry/789/comment/123', () => {59+ node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')60+ res = node.search('get', '/entry/789/comment/123')61+ expect(res).not.toBeNull()62+ expect(res.handler).toBe('get comment')63+ expect(res.params['id']).toBe('789')64+ expect(res.params['comment_id']).toBe('123')65+ })66+})67+68+describe('Wildcard', () => {69+ it('/wildcard-abc/xxxxxx/wildcard-efg', () => {70+ node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')71+ res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')72+ expect(res).not.toBeNull()73+ expect(res.handler).toBe('wildcard')74+ })75+})76+77+describe('Regexp', () => {78+ node.insert(79+ 'get',80+ '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}',81+ 'regexp'82+ )83+ it('/regexp-abc/123/comment/abc', () => {84+ res = node.search('get', '/regex-abc/123/comment/abc')85+ expect(res).not.toBeNull()86+ expect(res.handler).toBe('regexp')87+ expect(res.params['id']).toBe('123')88+ expect(res.params['comment_id']).toBe('abc')89+ })90+ it('/regexp-abc/abc', () => {91+ res = node.search('get', '/regex-abc/abc')92+ expect(res).toBeNull()93+ })94+ it('/regexp-abc/123/comment/123', () => {95+ res = node.search('get', '/regex-abc/123/comment/123')96+ expect(res).toBeNull()97+ })98+})99+100+describe('All', () => {101+ node.insert('all', '/all-methods', 'all methods')102+ it('/all-methods', () => {103+ res = node.search('get', '/all-methods')104+ expect(res).not.toBeNull()105+ expect(res.handler).toBe('all methods')106+ res = node.search('put', '/all-methods')107+ expect(res).not.toBeNull()108+ expect(res.handler).toBe('all methods')109+ })110+})modified:src/router.js+28 added-128 removed
11234556778910111213815161718192021229101112132526272829303132333435363738394041424314151617184647484950515253192021222324255657585960616263646566676869707172737475767778798081828384858687888926272829303132333435913637939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251263839401291301311321331341351364142434413914014114214314414545// Ref: https://github.com/bmf-san/goblinconst Node = require('./node')
class Router { constructor() { this.node = new Node({ label: "/" }) this.node = new Node() this.tempPath = '/' } add(method, path, handler) { return this.node.insert(method, path, handler); } match(method, path) { return this.node.search(method, path); }}
class Node { constructor({ label, method, handler, children } = {}) { this.label = label || ""; this.children = children || []; this.method = {}; if (method) { this['method'][method] = handler || {} } route(path) { this.tempPath = path return WrappedRouter(this) }
insert(method, path, handler) { let curNode = this if (path == '/') { curNode.label = path curNode['method'][method] = handler } const ps = this.splitPath(path) for (const p of ps) { let nextNode = curNode.children[p] if (nextNode) { curNode = nextNode } else { curNode.children[p] = new Node({ method: method, label: p, handler: handler, children: [] }) curNode = curNode.children[p] } } return this addRoute(method, path, handler) { this.node.insert(method, path, handler) return WrappedRouter(this) }
splitPath(path) { const ps = [] for (const p of path.split('/')) { if (p) { ps.push(p) } } return ps matchRoute(method, path) { method = method.toLowerCase() const res = this.node.search(method, path) return res }}
getPattern(label) { // :id{[0-9]+} → [0-9]+$ // :id → (.+) const match = label.match(/^\:.+?\{(.+)\}$/) if (match) { return '(' + match[1] + ')' } return '(.+)' }
getParamName(label) { const match = label.match(/^\:([^\{\}]+)/) if (match) { return match[1] } }
noRoute() { return null }
search(method, path) { let curNode = this const params = {}
for (const p of this.splitPath(path)) { const nextNode = curNode.children[p] if (nextNode) { curNode = nextNode continue } if (Object.keys(curNode.children).length == 0) { if (curNode.label != p) { return this.noRoute()const proxyHandler = { get: (target, prop) => (...args) => { if (target.constructor.prototype.hasOwnProperty(prop)) { return target[prop](...args) } else { if (args.length === 1) { return target.addRoute(prop, target.tempPath, ...args) } break return target.addRoute(prop, ...args) } let isParamMatch = false for (const key in curNode.children) { if (key == "*") { // Wildcard curNode = curNode.children[key] isParamMatch = true break } if (key.match(/^:/)) { const pattern = this.getPattern(key) const match = p.match(new RegExp(pattern)) if (match) { const k = this.getParamName(key) params[k] = match[0] curNode = curNode.children[key] isParamMatch = true break } return this.noRoute() } } if (isParamMatch == false) { return this.noRoute() } }
let handler = curNode['method']['all'] if (!handler) { handler = curNode['method'][method]; } if (!handler) { return this.noRoute() } return [handler, params] } },}
const proxyHandler = { get: (target, prop) => (...args) => { if (target.constructor.prototype.hasOwnProperty(prop)) { return target[prop](...args) } else { return target.add(prop, ...args) } }const WrappedRouter = (router = new Router()) => { return new Proxy(router, proxyHandler)}
const WrappedRouter = () => { return new Proxy( new Router(), proxyHandler )}
module.exports = WrappedRouterNo newline at end of filemodule.exports = WrappedRoutermodified:src/router.test.js+60 added-73 removed
1233456456788910111291011121415161314151618192021221718192425262728293031322021223435363738394041232444454647484950515253542526272829303132565758596061333435363738636465666768394041424344454647484950707172737475765152798081828384858687535455565758596061626364656667686970717273747576const Router = require('./router')let router = Router()
describe('root match', () => { let router = Router() let route = router.get('/', 'get handler') route = router.post('/', 'post handler')describe('Basic Usage', () => { it('get, post root', () => { router.get('/', 'get root') router.post('/', 'post root')
let match = router.match('get', '/') expect(match[0]).toBe('get handler') match = router.match('post', '/') expect(match[0]).toBe('post handler')}) let res = router.matchRoute('GET', '/') expect(res).not.toBeNull() expect(res.handler).toBe('get root')
describe.skip('all', () => { let router = Router() router.all('/hello', 'all hello') res = router.matchRoute('POST', '/') expect(res).not.toBeNull() expect(res.handler).toBe('post root')
let match = router.match('get', '/hello') expect(match[0]).toBe('all hello') match = router.match('post', '/hello') expect(match[0]).toBe('all hello')}) res = router.matchRoute('PUT', '/') expect(res).toBeNull()
describe.skip('', () => { let router = Router() it('/ match', () => { router.add('get', '/', 'root') let match = router.match('get', '/') expect(match).not.toBeNull() expect(match[0]).toBe('root') match = router.match('get', '/foo') expect(match).toBeNull() res = router.matchRoute('GET', '/nothing') expect(res).toBeNull() })
it('/hello match', () => { router.add('/hello', 'hello') match = router.match('/foo') expect(match).toBeNull() match = router.match('/hello') expect(match[0]).toBe('hello') })})
describe.skip('path match', () => { let router = Router() router.add('/entry/:id', 'entry-id') router.add('/entry/:id/:comment', 'entry-id-comment') router.add('/year/:year{[0-9]{4}}/:month{[0-9]{2}}', 'date-regex')
it('entry id match', () => { const match = router.match('/entry/123') expect(match[0]).toBe('entry-id') expect(match[1]['id']).toBe('123')describe('Complex', () => { it('Named Param', () => { router.get('/entry/:id', 'get entry') res = router.matchRoute('GET', '/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('get entry') expect(res.params['id']).toBe('123') })
it('entry id and comment match', () => { const match = router.match('/entry/123/45678') expect(match[0]).toBe('entry-id-comment') expect(match[1]['id']).toBe('123') expect(match[1]['comment']).toBe('45678') it('Wildcard', () => { router.get('/wild/*/card', 'get wildcard') res = router.matchRoute('GET', '/wild/xxx/card') expect(res).not.toBeNull() expect(res.handler).toBe('get wildcard') })
it('date-regex', () => { const match = router.match('/year/2021/12') expect(match[0]).toBe('date-regex') expect(match[1]['year']).toBe('2021') expect(match[1]['month']).toBe('12') it('Regexp', () => { router.get('/post/:date{[0-9]+}/:title{[a-z]+}', 'get post') res = router.matchRoute('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.matchRoute('GET', '/post/onetwothree') expect(res).toBeNull() res = router.matchRoute('GET', '/post/123/123') expect(res).toBeNull() })
it('not match', () => { let match = router.match('/foo') expect(match).toBeNull() match = router.match('/year/abc') expect(match).toBeNull() })})
describe.skip('wildcard', () => { let router = Router() it('match', () => { router = Router() router.add('/abc/*/def') let match = router.match('/abc/xxx/def') expect(match).not.toBeNull() match = router.match('/abc/xxx/abc') expect(match).toBeNull()describe('Chained Route', () => { it('Return rooter object', () => { router = router.patch('/', 'patch root') expect(router).not.toBeNull() router = router.delete('/', 'delete root') res = router.matchRoute('DELETE', '/') expect(res).not.toBeNull() expect(res.handler).toBe('delete root') }) it('Chain with route method', () => { router.route('/api/book').get('get book').post('post book').put('put book') res = router.matchRoute('GET', '/api/book') expect(res).not.toBeNull() expect(res.handler).toBe('get book') res = router.matchRoute('POST', '/api/book') expect(res).not.toBeNull() expect(res.handler).toBe('post book') res = router.matchRoute('PUT', '/api/book') expect(res).not.toBeNull() expect(res.handler).toBe('put book') res = router.matchRoute('DELETE', '/api/book') expect(res).toBeNull() })})modified:package.json+1 added-1 removed
19 unmodified lines20 "dependencies": {21 "global": "^4.4.0",22 "wrangler": "^0.0.0-beta.6"23 }24-}24+}