'use strict'; /** * Module dependencies. */ var contentDisposition = require('content-disposition'); var ensureErrorHandler = require('error-inject'); var getType = require('mime-types').contentType; var onFinish = require('on-finished'); var isJSON = require('koa-is-json'); var escape = require('escape-html'); var typeis = require('type-is').is; var statuses = require('statuses'); var destroy = require('destroy'); var assert = require('assert'); var path = require('path'); var vary = require('vary'); var extname = path.extname; /** * Prototype. */ module.exports = { /** * Return the request socket. * * @return {Connection} * @api public */ get socket() { return this.ctx.req.socket; }, /** * Return response header. * * @return {Object} * @api public */ get header() { return this.res._headers || {}; }, /** * Return response header, alias as response.header * * @return {Object} * @api public */ get headers() { return this.header; }, /** * Get response status code. * * @return {Number} * @api public */ get status() { return this.res.statusCode; }, /** * Set response status code. * * @param {Number} code * @api public */ set status(code) { assert('number' == typeof code, 'status code must be a number'); assert(statuses[code], 'invalid status code: ' + code); this._explicitStatus = true; this.res.statusCode = code; this.res.statusMessage = statuses[code]; if (this.body && statuses.empty[code]) this.body = null; }, /** * Get response status message * * @return {String} * @api public */ get message() { return this.res.statusMessage || statuses[this.status]; }, /** * Set response status message * * @param {String} msg * @api public */ set message(msg) { this.res.statusMessage = msg; }, /** * Get response body. * * @return {Mixed} * @api public */ get body() { return this._body; }, /** * Set response body. * * @param {String|Buffer|Object|Stream} val * @api public */ set body(val) { var original = this._body; this._body = val; // no content if (null == val) { if (!statuses.empty[this.status]) this.status = 204; this.remove('Content-Type'); this.remove('Content-Length'); this.remove('Transfer-Encoding'); return; } // set the status if (!this._explicitStatus) this.status = 200; // set the content-type only if not yet set var setType = !this.header['content-type']; // string if ('string' == typeof val) { if (setType) this.type = /^\s*' + url + '.'; return; } // text this.type = 'text/plain; charset=utf-8'; this.body = 'Redirecting to ' + url + '.'; }, /** * Set Content-Disposition header to "attachment" with optional `filename`. * * @param {String} filename * @api public */ attachment: function(filename){ if (filename) this.type = extname(filename); this.set('Content-Disposition', contentDisposition(filename)); }, /** * Set Content-Type response header with `type` through `mime.lookup()` * when it does not contain a charset. * * Examples: * * this.type = '.html'; * this.type = 'html'; * this.type = 'json'; * this.type = 'application/json'; * this.type = 'png'; * * @param {String} type * @api public */ set type(type) { type = getType(type) || false; if (type) { this.set('Content-Type', type); } else { this.remove('Content-Type'); } }, /** * Set the Last-Modified date using a string or a Date. * * this.response.lastModified = new Date(); * this.response.lastModified = '2013-09-13'; * * @param {String|Date} type * @api public */ set lastModified(val) { if ('string' == typeof val) val = new Date(val); this.set('Last-Modified', val.toUTCString()); }, /** * Get the Last-Modified date in Date form, if it exists. * * @return {Date} * @api public */ get lastModified() { var date = this.get('last-modified'); if (date) return new Date(date); }, /** * Set the ETag of a response. * This will normalize the quotes if necessary. * * this.response.etag = 'md5hashsum'; * this.response.etag = '"md5hashsum"'; * this.response.etag = 'W/"123456789"'; * * @param {String} etag * @api public */ set etag(val) { if (!/^(W\/)?"/.test(val)) val = '"' + val + '"'; this.set('ETag', val); }, /** * Get the ETag of a response. * * @return {String} * @api public */ get etag() { return this.get('ETag'); }, /** * Return the response mime type void of * parameters such as "charset". * * @return {String} * @api public */ get type() { var type = this.get('Content-Type'); if (!type) return ''; return type.split(';')[0]; }, /** * Check whether the response is one of the listed types. * Pretty much the same as `this.request.is()`. * * @param {String|Array} types... * @return {String|false} * @api public */ is: function(types){ var type = this.type; if (!types) return type || false; if (!Array.isArray(types)) types = [].slice.call(arguments); return typeis(type, types); }, /** * Return response header. * * Examples: * * this.get('Content-Type'); * // => "text/plain" * * this.get('content-type'); * // => "text/plain" * * @param {String} field * @return {String} * @api public */ get: function(field){ return this.header[field.toLowerCase()] || ''; }, /** * Set header `field` to `val`, or pass * an object of header fields. * * Examples: * * this.set('Foo', ['bar', 'baz']); * this.set('Accept', 'application/json'); * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); * * @param {String|Object|Array} field * @param {String} val * @api public */ set: function(field, val){ if (2 == arguments.length) { if (Array.isArray(val)) val = val.map(String); else val = String(val); this.res.setHeader(field, val); } else { for (var key in field) { this.set(key, field[key]); } } }, /** * Append additional header `field` with value `val`. * * Examples: * * this.append('Link', ['', '']); * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); * this.append('Warning', '199 Miscellaneous warning'); * * @param {String} field * @param {String|Array} val * @api public */ append: function(field, val){ var prev = this.get(field); if (prev) { val = Array.isArray(prev) ? prev.concat(val) : [prev].concat(val); } return this.set(field, val); }, /** * Remove header `field`. * * @param {String} name * @api public */ remove: function(field){ this.res.removeHeader(field); }, /** * Checks if the request is writable. * * @return {Boolean} * @api private */ get writable() { // can't write any more after response finished if (this.res.finished) return false; var socket = this.res.socket; // There are already pending outgoing res, but still writable // https://github.com/nodejs/node/blob/v4.4.7/lib/_http_server.js#L486 if (!socket) return true; return socket.writable; }, /** * Inspect implementation. * * @return {Object} * @api public */ inspect: function(){ if (!this.res) return; var o = this.toJSON(); o.body = this.body; return o; }, /** * Return JSON representation. * * @return {Object} * @api public */ toJSON: function(){ return { status: this.status, message: this.message, header: this.header }; } };