Skip to content

Commit

Permalink
fix(wobe): call wildcard route only with good http method (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
coratgerl authored Jul 28, 2024
1 parent 118e386 commit b8c1185
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
28 changes: 28 additions & 0 deletions packages/wobe/src/Wobe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,34 @@ describe('Wobe', () => {
expect(mockOptions).toHaveBeenCalledTimes(1)
})

it('should not run hook on all routes (with not the same http method) when specified on specific route with * path', async () => {
const fakeRouteHook = mock(() => {})

const localWobe = new Wobe()
const localPort = await getPort()

localWobe.get('*', () => new Response(null), fakeRouteHook)
localWobe.get('/tata', () => new Response('tata'))
localWobe.post('/toto', (ctx) => {
return ctx.res.send('test')
})

localWobe.listen(localPort)

await fetch(`http://127.0.0.1:${localPort}/tata`)

expect(fakeRouteHook).toHaveBeenCalledTimes(1)

const res = await fetch(`http://127.0.0.1:${localPort}/toto`, {
method: 'POST',
})

expect(await res.text()).toEqual('test')
expect(fakeRouteHook).toHaveBeenCalledTimes(1)

localWobe.stop()
})

it('should create wobe app with custom context', async () => {
const wobeWithContext = new Wobe<{
customType: string
Expand Down
17 changes: 14 additions & 3 deletions packages/wobe/src/router/RadixTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ export class RadixTree {
'Cannot add hooks after the tree has been optimized',
)

const pathParts = path.split('/').filter(Boolean)
let currentNode = node || this.root

// For hooks with no specific path
Expand All @@ -120,10 +119,21 @@ export class RadixTree {
for (let i = 0; i < currentNode.children.length; i++) {
const child = currentNode.children[i]

addHookToChildren(child)
if (
child.handler &&
(method === child.method || method === 'ALL')
) {
this._addHookToNode(child, hook, handler)
}

if (child.children.length > 0) addHookToChildren(child)
}

return
}

const pathParts = path.split('/').filter(Boolean)

for (let i = 0; i < pathParts.length; i++) {
const pathPart = pathParts[i]
const isWildcardNode = pathPart[0] === '*'
Expand Down Expand Up @@ -218,7 +228,8 @@ export class RadixTree {
// If the child has no children and the node is a wildcard or parameter node
if (
isChildWildcardOrParameterNode &&
child.children.length === 0
child.children.length === 0 &&
child.method === method
)
return child

Expand Down

0 comments on commit b8c1185

Please sign in to comment.