Skip to content

Instantly share code, notes, and snippets.

@develmts
Last active November 22, 2016 16:23
Show Gist options
  • Save develmts/a3c1f89c8327f33f143da230ad52c7ae to your computer and use it in GitHub Desktop.
Save develmts/a3c1f89c8327f33f143da230ad52c7ae to your computer and use it in GitHub Desktop.
Sample of mixing middleware
var router = require('koa-router')({prefix: '/api'}); // << important
router.get('/something', function *(next ){
this.body = yield getSomething()
});
router.get('/somewhere', function *(next ){
this.body = yield someWhere()
});
//... more like above, probably
module.exports = router
/* /app/router.js */
"use strict;"
var serve = require('koa-static')
var WEBROOT= '/public'
var router = require('koa-router')();
// home redirect
router.redirect('/', '/index.html')
// Serve html static files
router.get('/index.html', serve(WEBROOT+'/'))
router.get('/info.html', serve(WEBROOT+'/'))
// complex, probably render engine based pages
router.get('/complex.html', fucnhtion *(next){
// your own bussines here
this.body = yield this.render('complex');
})
// -- more like previous, probably
// nest the api router at the end
var apiRouter = require(appRoot+'/app/apirouter')
router.use(apiRouter.routes() )
router.use(apiRouter.allowedMethods() )
module.exports = router
"use strict;"
var path = require('path');
var http = require('http')
var rewrite = require('koa-rewrite')
var serve = require('koa-static')
var views = require('koa-view')
var WEBROOT= '/public'
var ASSETS = WEEBROOT+'/assets'
var app ={},
server = {},
port = 3000;
function start(){
app = require('koa')()
server = http.createServer(this.app.callback())
// rewriting
app.use(rewrite('/js/*', ASSETS+'/js/$1'))
// static assets
app.use(serve(ASSETS))
// insert your view engine before the routes
app.use(views('./views'))
// routes
var mainRouter = require('/app/router')
app.use( mainRouter.routes())
app.use( mainRouter.allowedMethods())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment