Pass the tests
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 265a90e · Browse files · 6 files·+149 added−73 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+149 added−73 removed
- tests:+38 added−17 removed
- other:+111 added−56 removed
Provenance
- Commit
072196c- Tree
a07a2ac- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent
265a90e
6 files changed+149 added−73 removed
modified:example/basic/index.js+43 added
24 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707124 unmodified lines})
// addEventListenerapp.fire()
//
const logger = (c, next) => { console.log(`Req: [${c.req.method}] ${c.req.url}`) next() console.log(`Respond`)}
const auth = (c, next) => { const url = new URL(c.req.url) if (!url.pathname.match(/\/admin*/)) { next() } const auth = c.req.headers.get('x-auth') if (auth != 'auth-path') { return c.notFound() } next()}
const hello = (c, next) => { next() c.res.headers.append('x-message', 'Hello!')}
const notFound = (c, next) => { next() if (res.status === 404) { c.res = new Response('Not Found', { status: 404, }) }}
app.use('*', logger)app.use('*', notFound)app.use('/hello', hello)app.use('/admin/*', auth)
app.get('/admin', () => 'Your are Admin!')
const handler = app.matchRoute('GET', '/admin')modified:src/hono.js+16 added-5 removed
42 unmodified lines4344454647484950519 unmodified lines61626364656667686970717273747576777879808182836 unmodified lines90919293949596979887888999100101102103104929310510610710830 unmodified lines42 unmodified linesclass App { constructor() { this.router = new Router() this.middlewareRouter = new Router() this.middlewareRouters = [] }
addRoute(method, path, ...args) { this.router.add(method, path, ...args)9 unmodified lines return WrappedApp(this) }
use(path, middleware) { const router = new Router() router.add('all', path, middleware) this.middlewareRouters.push(router) }
/* use(path, middleware) { middleware = [middleware] const result = this.middlewareRouter.match('all', path) if (result) { middleware.push(...result.handler) } this.middlewareRouter.add('all', path, ...middleware) } */
// XXX createContext(req, res) { return { req: req, res: res }6 unmodified lines if (!result) return this.notFound()
request.params = (key) => result.params[key]
let handler = result.handler[0] // XXX
const middleware = [defaultFilter]
for (const mr of this.middlewareRouters) { const mwResult = this.middlewareRouter.match('all', path) if (mwResult) { middleware.push(...mwResult.handler) const mwResult = mr.match('all', path) if (mwResult) { middleware.push(...mwResult.handler) } }
let handler = result.handler[0] // XXX
let wrappedHandler = (context, next) => { context.res = handler(context) next() }30 unmodified linesmodified:src/node.js+25 added-51 removed
1+const { splitPath, getPattern, getParamName } = require('./util')2+3 const METHOD_NAME_OF_ALL = 'all'4 5 const createResult = (handler, params) => {6 return { handler: handler, params: params }10 unmodified lines17 }18 19 insert(method, path, handler) {20 let curNode = this19- for (const p of this.splitPath(path)) {20- let nextNode = curNode.children[p]21+ for (const p of splitPath(path)) {22+ const nextNode = curNode.children[p]23 if (nextNode) {24 curNode = nextNode23- } else {24- curNode.children[p] = new Node({25- label: p,26- handler: handler,27- })28- curNode = curNode.children[p]25+ continue26 }27+ curNode.children[p] = new Node({28+ label: p,29+ method: method,30+ handler: handler,31+ })32+ curNode = curNode.children[p]33 }34 curNode.method[method] = handler35+ return curNode36 }37 34- splitPath(path) {35- return ['/', ...path.split('/').filter((p) => p !== '')]36- }37-38- getPattern(label) {39- // :id{[0-9]+} → [0-9]+$40- // :id → (.+)41- const match = label.match(/^\:.+?\{(.+)\}$/)42- if (match) {43- return '(' + match[1] + ')'44- }45- return '(.+)'46- }47-48- getParamName(label) {49- const match = label.match(/^\:([^\{\}]+)/)50- if (match) {51- return match[1]52- }53- }54-38 search(method, path) {39 let curNode = this57- let handler58- let params = {}40+ const params = {}41+ const parts = splitPath(path)42 60- if (path === '/') {61- const root = this.children['/']62- if (!root) return this.noRoute()63- // app.get('*', () => 'All')64- const rootAsterisk = root.children['*']65- if (rootAsterisk) {66- handler =67- rootAsterisk.method[method] || rootAsterisk.method[METHOD_NAME_OF_ALL]68- } else if (!root.method[method]) {69- return this.noRoute()70- }71- }43+ for (const [i, p] of parts.entries()) {44+ const nextNode = curNode.children[p]45 73- for (const p of this.splitPath(path)) {74- let nextNode = curNode.children[p]75-46 if (nextNode) {47 curNode = nextNode48 continue49 }50 51 let isParamMatch = false52 for (const key in curNode.children) {53+ // Wildcard54 if (key === '*') {84- // Wildcard55 curNode = curNode.children[key]56 isParamMatch = true57 break58 } else if (key.match(/^:/)) {89- const pattern = this.getPattern(key)59+ const pattern = getPattern(key)60 const match = p.match(new RegExp(pattern))61 if (match) {92- const k = this.getParamName(key)62+ const k = getParamName(key)63 params[k] = match[0]64 curNode = curNode.children[key]65 isParamMatch = true66 break67 }68 return this.noRoute()69 }70 }71+72 if (isParamMatch == false) {73 return this.noRoute()74 }75+76+ if (i === parts.length - 1) {77+ break78+ }79 }80 106- handler =107- handler || curNode.method[METHOD_NAME_OF_ALL] || curNode.method[method]81+ const handler = curNode.method[METHOD_NAME_OF_ALL] || curNode.method[method]82 83 if (!handler) {84 return this.noRoute()85 }10 unmodified linesmodified:src/node.test.js+8 added-17 removed
1 const Node = require('./node')2 3-describe('Util Methods', () => {4- const node = new Node()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-3 describe('Root Node', () => {4 const node = new Node()5 node.insert('get', '/', 'get root')6 it('get /', () => {18- expect(node.search('get', '/')).not.toBeNull()7+ let 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 23-describe('Root Node', () => {14+describe('Root Node id 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 31-describe('All', () => {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()41 unmodified lines68 })69 70 it('get /entry/456/comment', () => {71 node.insert('get', '/entry/:id', 'get entry')81- res = node.search('get', '/entry/456/comment')72+ let res = node.search('get', '/entry/456/comment')73 expect(res).toBeNull()74 })75 76 it('get /entry/789/comment/123', () => {77 node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')87- res = node.search('get', '/entry/789/comment/123')78+ let res = node.search('get', '/entry/789/comment/123')79 expect(res).not.toBeNull()80 expect(res.handler).toBe('get comment')81 expect(res.params['id']).toBe('789')82 expect(res.params['comment_id']).toBe('123')3 unmodified lines86 describe('Wildcard', () => {87 const node = new Node()88 it('/wildcard-abc/xxxxxx/wildcard-efg', () => {89 node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')99- res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')90+ let res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')91 expect(res).not.toBeNull()92 expect(res.handler).toBe('wildcard')93 })94 })37 unmodified linesadded:src/util.js+27 added
123456789101112131415161718192021222324252627const splitPath = (path) => { path = path.replace(/^\//, '') return path.split('/')}
const getPattern = (label) => { // :id{[0-9]+} => ([0-9]+) // :id => (.+) const match = label.match(/^\:.+?\{(.+)\}$/) if (match) { return '(' + match[1] + ')' } return '(.+)'}
const getParamName = (label) => { const match = label.match(/^\:([^\{\}]+)/) if (match) { return match[1] }}
module.exports = { splitPath, getPattern, getParamName,}added:src/util.test.js+30 added
1+const { splitPath, getPattern, getParamName } = require('./util')2+3+describe('Utility methods', () => {4+ it('splitPath', () => {5+ let ps = splitPath('/')6+ expect(ps[0]).toBe('')7+ ps = splitPath('/hello')8+ expect(ps[0]).toBe('hello')9+ ps = splitPath('*')10+ expect(ps[0]).toBe('*')11+ ps = splitPath('/wildcard-abc/*/wildcard-efg')12+ expect(ps[0]).toBe('wildcard-abc')13+ expect(ps[1]).toBe('*')14+ expect(ps[2]).toBe('wildcard-efg')15+ })16+17+ it('getPattern', () => {18+ let res = getPattern(':id')19+ expect(res).toBe('(.+)')20+ res = getPattern(':id{[0-9]+}')21+ expect(res).toBe('([0-9]+)')22+ })23+24+ it('getParamName', () => {25+ let res = getParamName(':id')26+ expect(res).toBe('id')27+ res = getParamName(':id{[0-9]+}')28+ expect(res).toBe('id')29+ })30+})