Skip to content

Commit

Permalink
released v0.9.7 - added test to verify multi-route waterfall middlewa…
Browse files Browse the repository at this point in the history
…re and added README example
  • Loading branch information
kwhitley committed May 4, 2020
1 parent 543682a commit c4b3631
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,6 @@ addEventListener('fetch', event => event.respondWith(router.handle(event.request
### Multiple Route Handlers as Middleware
###### Note: Any of these handlers may be awaitable async functions!
```js
import { Router } from 'itty-router'

// create a router
const router = Router() // note the intentional lack of "new"

// withUser modifies original request, then continues without returning
const withUser = (req) => {
req.user = { name: 'Mittens', age: 3 }
Expand All @@ -145,6 +140,20 @@ router.handle({ url: 'https://example.com/pass/user' }) // --> STATUS 200: { nam
router.handle({ url: 'https://example.com/fail/user' }) // --> STATUS 401: Not Authenticated
```
### Multi-route (Upstream) Middleware
```js
// withUser modifies original request, then continues without returning
const withUser = (req) => {
req.user = { name: 'Mittens', age: 3 }
}

router
.get('*', withUser) // embeds user before all other matching routes
.get('/user', (req) => new Response(JSON.stringify(req.user))) // user embedded already!

router.handle({ url: 'https://example.com/user' }) // --> STATUS 200: { name: 'Mittens', age: 3 }
```
## Testing & Contributing
1. fork repo
2. add code
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "itty-router",
"version": "0.9.6",
"version": "0.9.7",
"description": "Tiny, zero-dependency router with route param and query parsing.",
"main": "dist/itty-router.min.js",
"files": [
Expand Down
18 changes: 18 additions & 0 deletions src/itty-router.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,23 @@ describe('Router', () => {
router.handle({ method: 'CUSTOM', url: 'https://example.com/foo' }), // no method listed
).not.toThrow()
})

it('can match multiple routes if earlier handlers do not return (as middleware)', async () => {
const r = Router()

const middleware = req => {
req.user = { id: 13 }
}

const handler = jest.fn((req) => req.user.id)

r.get('/middleware/*', middleware)
r.get('/middleware/:id', handler)

await r.handle(buildRequest({ path: '/middleware/foo' }))

expect(handler).toHaveBeenCalled()
expect(handler).toHaveReturnedWith(13)
})
})
})

0 comments on commit c4b3631

Please sign in to comment.