Skip to content

oreofish/koa-if

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-if

Conditionally run middleware in Koa

Note: only tested with the new async/await style middleware in koa 2

Install

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:

import Koa from 'koa'
import test from 'koa-if'

const app = new Koa()

async function normalMiddleware(ctx, next) {
  if (!ctx.body) ctx.body = '<h1>Normal</h1>'
  await next()
}

async function specialMiddleware(ctx, next) {
  if (!ctx.body) ctx.body = '<h1>Special</h2>'
  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

About

Conditionally run middleware in Koa

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%