koa-lite/lib/application.js

224 lines
4.9 KiB
JavaScript
Raw Normal View History

'use strict';
2013-08-17 07:15:57 +00:00
/**
* Module dependencies.
*/
const debug = require('debug')('koa:application');
const Emitter = require('events').EventEmitter;
const compose_es7 = require('composition');
const onFinished = require('on-finished');
const response = require('./response');
const compose = require('koa-compose');
const isJSON = require('koa-is-json');
const context = require('./context');
const request = require('./request');
const statuses = require('statuses');
const Cookies = require('cookies');
const accepts = require('accepts');
const assert = require('assert');
const Stream = require('stream');
const http = require('http');
const only = require('only');
const co = require('co');
2013-08-17 07:15:57 +00:00
/**
* Application prototype.
*/
const app = Application.prototype;
2013-08-17 07:15:57 +00:00
/**
* Expose `Application`.
*/
module.exports = Application;
2013-08-17 07:15:57 +00:00
/**
* Initialize a new `Application`.
*
* @api public
*/
function Application() {
if (!(this instanceof Application)) return new Application;
this.env = process.env.NODE_ENV || 'development';
this.subdomainOffset = 2;
this.middleware = [];
this.context = Object.create(context);
this.request = Object.create(request);
this.response = Object.create(response);
2013-08-17 07:15:57 +00:00
}
/**
* Inherit from `Emitter.prototype`.
*/
Object.setPrototypeOf(Application.prototype, Emitter.prototype);
2013-08-17 07:15:57 +00:00
/**
* Shorthand for:
*
* http.createServer(app.callback()).listen(...)
*
* @param {Mixed} ...
* @return {Server}
* @api public
*/
app.listen = function(){
2013-11-27 05:26:05 +00:00
debug('listen');
const server = http.createServer(this.callback());
2013-08-17 07:15:57 +00:00
return server.listen.apply(server, arguments);
};
2014-03-11 18:01:33 +00:00
/**
* Return JSON representation.
* We only bother showing settings.
2014-03-11 18:01:33 +00:00
*
* @return {Object}
* @api public
*/
app.inspect =
2014-03-11 18:01:33 +00:00
app.toJSON = function(){
return only(this, [
'subdomainOffset',
'env'
]);
};
2013-08-17 07:15:57 +00:00
/**
* Use the given middleware `fn`.
*
* @param {GeneratorFunction} fn
2013-08-17 07:15:57 +00:00
* @return {Application} self
* @api public
*/
app.use = function(fn){
if (!this.experimental) {
// es7 async functions are allowed
assert(fn && 'GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function');
}
2013-12-30 00:04:06 +00:00
debug('use %s', fn._name || fn.name || '-');
2013-08-17 07:15:57 +00:00
this.middleware.push(fn);
return this;
};
/**
* Return a request handler callback
2013-08-30 21:09:18 +00:00
* for node's native http server.
2013-08-17 07:15:57 +00:00
*
* @return {Function}
* @api public
*/
app.callback = function(){
const fn = this.experimental
? compose_es7(this.middleware)
: co.wrap(compose(this.middleware));
2013-08-17 07:15:57 +00:00
2014-05-02 00:46:09 +00:00
if (!this.listeners('error').length) this.on('error', this.onerror);
2015-10-09 04:49:17 +00:00
return (req, res) => {
res.statusCode = 404;
2015-10-09 04:49:17 +00:00
const ctx = this.createContext(req, res);
onFinished(res, ctx.onerror);
fn.call(ctx).then(function () {
respond.call(ctx);
}).catch(ctx.onerror);
2013-08-17 07:15:57 +00:00
}
};
/**
* Initialize a new context.
*
* @api private
*/
app.createContext = function(req, res){
const context = Object.create(this.context);
const request = context.request = Object.create(this.request);
const response = context.response = Object.create(this.response);
context.app = request.app = response.app = this;
context.req = request.req = response.req = req;
context.res = request.res = response.res = res;
request.ctx = response.ctx = context;
request.response = response;
response.request = request;
context.onerror = context.onerror.bind(context);
context.originalUrl = request.originalUrl = req.url;
2013-11-15 18:03:40 +00:00
context.cookies = new Cookies(req, res, this.keys);
context.accept = request.accept = accepts(req);
context.state = {};
return context;
2013-11-15 18:09:56 +00:00
};
2013-08-22 02:47:56 +00:00
/**
* Default error handler.
*
* @param {Error} err
* @api private
*/
app.onerror = function(err){
assert(err instanceof Error, `non-error thrown: ${err}`);
2015-08-20 18:28:40 +00:00
if (404 == err.status || err.expose) return;
if (this.silent) return;
// DEPRECATE env-specific logging in v2
if ('test' == this.env) return;
const msg = err.stack || err.toString();
2014-05-01 23:18:40 +00:00
console.error();
console.error(msg.replace(/^/gm, ' '));
2014-05-01 23:18:40 +00:00
console.error();
2013-08-22 02:47:56 +00:00
};
2013-08-17 07:15:57 +00:00
/**
* Response helper.
2013-08-17 07:15:57 +00:00
*/
function respond() {
2014-04-15 15:39:40 +00:00
// allow bypassing koa
if (false === this.respond) return;
const res = this.res;
if (res.headersSent || !this.writable) return;
2013-12-22 17:26:21 +00:00
var body = this.body;
const code = this.status;
// ignore body
if (statuses.empty[code]) {
// strip headers
this.body = null;
return res.end();
}
2013-08-17 07:15:57 +00:00
2014-04-15 02:06:32 +00:00
if ('HEAD' == this.method) {
if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body));
return res.end();
}
2014-04-15 15:39:40 +00:00
// status body
2014-04-15 02:06:32 +00:00
if (null == body) {
this.type = 'text';
body = this.message || String(code);
2015-03-29 03:53:54 +00:00
this.length = Buffer.byteLength(body);
2014-04-13 02:23:57 +00:00
return res.end(body);
}
2013-08-17 07:15:57 +00:00
2014-04-15 15:39:40 +00:00
// responses
2014-04-15 02:06:32 +00:00
if (Buffer.isBuffer(body)) return res.end(body);
if ('string' == typeof body) return res.end(body);
if (body instanceof Stream) return body.pipe(res);
2013-08-17 07:15:57 +00:00
// body: json
body = JSON.stringify(body);
this.length = Buffer.byteLength(body);
res.end(body);
2014-03-24 18:21:15 +00:00
}