Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fusepilot/koa-if
Conditionally run middleware in Koa
https://github.com/fusepilot/koa-if
Last synced: 2 months ago
JSON representation
Conditionally run middleware in Koa
- Host: GitHub
- URL: https://github.com/fusepilot/koa-if
- Owner: fusepilot
- Created: 2015-11-20T04:05:18.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2015-11-21T04:17:35.000Z (about 9 years ago)
- Last Synced: 2024-04-23T23:14:58.259Z (8 months ago)
- Language: JavaScript
- Size: 4.88 KB
- Stars: 3
- Watchers: 1
- Forks: 3
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# koa-if
Conditionally run middleware in Koa
*Note: only tested with the new async/await style middleware in koa 2*
## Install
```bash
npm install --save koa-if
```## API
* `middleware` middleware to run if condition is truthy.
* `condition` either a boolean or a function that returns a boolean. Functions are passed the current context.## Usage:
```javascript
import Koa from 'koa'
import test from 'koa-if'const app = new Koa()
async function normalMiddleware(ctx, next) {
if (!ctx.body) ctx.body = 'Normal
'
await next()
}async function specialMiddleware(ctx, next) {
if (!ctx.body) ctx.body = 'Special'
await next()
}app.use(normalMiddleware)
// only run specialMiddleware on /special
app.use(test(specialMiddleware, (ctx) => {
return ctx.url == '/special'
}))app.listen(3000)
```Now, ````localhost:3000/special```` will show "Special" while all other urls will show "Normal".
## License
MIT