koa-better-vhost

0.0.1 • Public • Published

koa-better-vhost

Node version NPM version Dependency Status Travis CI Codecov

vhost for koajs.

Forked from koa-vhost.

Install

npm i koa-better-vhost

Example

const koa = require('koa')
const Router = require('koa-router')
const vhost = require('koa-better-vhost')
 
const main = koa()
main.use(require('koa-compress')())
main.use(function* (next) {
  this.today = new Date
  yield next
})
 
let vhosts = []
 
let homepage = koa()
let homepageRouter = new Router()
homepageRouter.get('/', function* (next) {
  // `this` is shared between main and homepage applications
  this.body = `Hello ${this.today.toUTCString()}`
  yield next
})
 
homepage.use(homepageRouter.routes())
 
vhosts.push({
  host: 'example.com',
  app: homepage
})
 
let api = koa()
api.use(function* auth (next) {
  // Do some auth job
  yield next
})
 
let apiRouter = new Router()
apiRouter.get('/', function* (next) {
  /**
   * Because we set this vhost is isolated, `this` is NOT shared between main and api applications
   * But `koa-compress` is still working
   */
  console.info(typeof this.today) // undefined
  this.body = `Hello from API`
  yield next
})
api.use(apiRouter.routes())
 
vhosts.push({
  host: /^api\.example\.com$/i,
  app: api,
  isolated: true
})
 
main.use(vhost(vhosts))

Readme

Keywords

none

Package Sidebar

Install

npm i koa-better-vhost

Weekly Downloads

3

Version

0.0.1

License

MIT

Last publish

Collaborators

  • chrisyipw