4. Koa
Koa is a new web framework designed by the team
behind Express, which aims to be a smaller, more
expressive, and more robust foundation for web
applications and APIs.
Through leveraging generators Koa allows you to ditch
callbacks and greatly increase error-handling.
Koa does not bundle any middleware within core, and
provides an elegant suite of methods that make writing
servers fast and enjoyable.
Via. http://koajs.com/
11. Koa要件
To use Koa you must be running node 0.11.9 or higher
for generator support
$ alias node='node --harmony'
package.json
"scripts": {
"start": "node --harmony app.js"
}
12. Koa sample
var koa = require('koa'),
app = koa();
app.use(function *() {
// Here is the important bit of application logic for this example.
// We make use of a series of async operations without callbacks.
var city = yield geolocation.getCityAsync(this.req.ip);・・・①
var forecast = yield weather.getForecastAsync(city);・・・②
this.body = 'Today, ' + city + ' will be ' + forecast.temperature
+ ' degrees.';・・・③
});
app.listen(8080);
Via. http://blog.stevensanderson.com/2013/12/21/
experiments-with-koa-and-javascript-generators/
16. Koa sample
app.use(function *() {
var tasks = {
imposeMinimumResponseTime: delay(500),
fetchWebPage: doHttpRequest('http://example.com/'),
squareTenSlowly: getSquareValueThunk(10)
};
// All of the operations have already started. Yielding
// the key-value object to Koa just makes it wait for them.
var results = yield tasks;
this.body = 'OK, all done.';
this.body += 'nResult of waiting is: ' + results.imposeMinimumResponseTime; // ①
Displays: undefined
this.body += 'nWeb page status code is: ' + results.fetchWebPage.statusCode; //
② Displays: Typically 200 in this case
this.body += 'nSquare of ten is: ' + results.squareTenSlowly; // ③ Displays: 100
});
Via. http://blog.stevensanderson.com/2013/12/21/
experiments-with-koa-and-javascript-generators/
26. Koa log middleware
// x-response-time
!
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
Via. http://dailyjs.com/2014/01/09/koa/
27. middleware
request
yield next;
yield next;
yield next;
middleware
middleware
middleware
try catch(e)
error
error
var start = new Date;
var ms = new Date - start;
response
response
response
response
middleware
error