Skip to content

Instantly share code, notes, and snippets.

@eljefedelrodeodeljefe
Last active May 23, 2016 20:09
Show Gist options
  • Save eljefedelrodeodeljefe/7bab8f516c964e9cceae to your computer and use it in GitHub Desktop.
Save eljefedelrodeodeljefe/7bab8f516c964e9cceae to your computer and use it in GitHub Desktop.
Basic Koa API and Web Server
This is my basic starting point for any koa server. Mostly for module development with frontend components
var koa = require('koa');
var app = koa();
var route = require('koa-route');
var send = require('koa-send');
var db = {
tobi: { name: 'tobi', species: 'ferret' },
loki: { name: 'loki', species: 'ferret' },
jane: { name: 'jane', species: 'ferret' }
};
app.use(route.get('/', index));
app.use(route.get('/pets', list));
app.use(route.get('/pets/:name', show));
app.listen(3000);
console.log('listening on port 3000');
function* index(){
yield send(this, '/index.html', { root: __dirname });
}
function* list(){
var names = Object.keys(db);
this.body = 'pets: ' + names.join(', ');
}
function* show(name){
var pet = db[name];
if (!pet) return this.throw('cannot find that pet', 404);
this.body = pet.name + ' is a ' + pet.species;
}
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('nodemon');
gulp.task('nodemon', function () {
return nodemon({ script: 'example/app.js', ext: 'html js' })
.on('restart', function () {
console.log('restarted!')
})
})
gulp.task('browser-sync', ['nodemon'], function() {
browserSync({
proxy: "localhost:3000", // local node app address
port: 4000, // use *different* port than above
notify: true
});
});
gulp.task('nodemon', function (cb) {
var called = false;
return nodemon({
script: 'example/app.js',
ignore: [
'Gulpfile.js',
'node_modules/'
]
})
.on('start', function () {
if (!called) {
called = true;
cb();
}
})
.on('restart', function () {
setTimeout(function () {
reload({ stream: false });
}, 1000);
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(['example/**/*.html'], reload);
gulp.watch(['example/**/*.js'], reload);
gulp.watch(['index.js'], ['bundle']);
gulp.watch(['example/**/*.css'], reload);
});
gulp.task('test', [], function () {
});
gulp.task('deploy', [], function () {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment