diff --git a/docs/api/index.md b/docs/api/index.md index b8b7ebe..010d4d4 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -112,9 +112,22 @@ app.listen(3000); the following are supported: - `app.env` defaulting to the __NODE_ENV__ or "development" + - `app.keys` array of signed cookie keys - `app.proxy` when true proxy header fields will be trusted - `app.subdomainOffset` offset of `.subdomains` to ignore [2] + You can pass the settings to the constructor: + ```js + const Koa = require('koa'); + const app = new Koa({ proxy: true }); + ``` + or dynamically: + ```js + const Koa = require('koa'); + const app = new Koa(); + app.proxy = true; + ``` + ## app.listen(...) A Koa application is not a 1-to-1 representation of an HTTP server. diff --git a/lib/application.js b/lib/application.js index 1854f37..a1f607f 100644 --- a/lib/application.js +++ b/lib/application.js @@ -34,13 +34,23 @@ module.exports = class Application extends Emitter { * @api public */ - constructor() { - super(); + /** + * + * @param {object} [options] Application options + * @param {string} [options.env='development'] Environment + * @param {string[]} [options.keys] Signed cookie keys + * @param {boolean} [options.proxy] Trust proxy headers + * @param {number} [options.subdomainOffset] Subdomain offset + * + */ - this.proxy = false; + constructor(options = {}) { + super(); + this.proxy = options.proxy || false; this.middleware = []; - this.subdomainOffset = 2; - this.env = process.env.NODE_ENV || 'development'; + this.subdomainOffset = options.subdomainOffset || 2; + this.env = options.env || process.env.NODE_ENV || 'development'; + this.keys = options.keys || undefined; this.context = Object.create(context); this.request = Object.create(request); this.response = Object.create(response); diff --git a/test/application/index.js b/test/application/index.js index 51d76ba..ff27111 100644 --- a/test/application/index.js +++ b/test/application/index.js @@ -53,4 +53,28 @@ describe('app', () => { process.env.NODE_ENV = NODE_ENV; assert.equal(app.env, 'development'); }); + + it('should set env from the constructor', () => { + const env = 'custom'; + const app = new Koa({ env }); + assert.strictEqual(app.env, env); + }); + + it('should set proxy flag from the constructor', () => { + const proxy = true; + const app = new Koa({ proxy }); + assert.strictEqual(app.proxy, proxy); + }); + + it('should set signed cookie keys from the constructor', () => { + const keys = ['customkey']; + const app = new Koa({ keys }); + assert.strictEqual(app.keys, keys); + }); + + it('should set subdomainOffset from the constructor', () => { + const subdomainOffset = 3; + const app = new Koa({ subdomainOffset }); + assert.strictEqual(app.subdomainOffset, subdomainOffset); + }); });