context.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. const util = require('util');
  6. const createError = require('http-errors');
  7. const httpAssert = require('http-assert');
  8. const delegate = require('delegates');
  9. const statuses = require('statuses');
  10. const Cookies = require('cookies');
  11. const COOKIES = Symbol('context#cookies');
  12. /**
  13. * Context prototype.
  14. */
  15. const proto = module.exports = {
  16. /**
  17. * util.inspect() implementation, which
  18. * just returns the JSON output.
  19. *
  20. * @return {Object}
  21. * @api public
  22. */
  23. inspect() {
  24. if (this === proto) return this;
  25. return this.toJSON();
  26. },
  27. /**
  28. * Return JSON representation.
  29. *
  30. * Here we explicitly invoke .toJSON() on each
  31. * object, as iteration will otherwise fail due
  32. * to the getters and cause utilities such as
  33. * clone() to fail.
  34. *
  35. * @return {Object}
  36. * @api public
  37. */
  38. toJSON() {
  39. return {
  40. request: this.request.toJSON(),
  41. response: this.response.toJSON(),
  42. app: this.app.toJSON(),
  43. originalUrl: this.originalUrl,
  44. req: '<original node req>',
  45. res: '<original node res>',
  46. socket: '<original node socket>'
  47. };
  48. },
  49. /**
  50. * Similar to .throw(), adds assertion.
  51. *
  52. * this.assert(this.user, 401, 'Please login!');
  53. *
  54. * See: https://github.com/jshttp/http-assert
  55. *
  56. * @param {Mixed} test
  57. * @param {Number} status
  58. * @param {String} message
  59. * @api public
  60. */
  61. assert: httpAssert,
  62. /**
  63. * Throw an error with `status` (default 500) and
  64. * `msg`. Note that these are user-level
  65. * errors, and the message may be exposed to the client.
  66. *
  67. * this.throw(403)
  68. * this.throw(400, 'name required')
  69. * this.throw('something exploded')
  70. * this.throw(new Error('invalid'))
  71. * this.throw(400, new Error('invalid'))
  72. *
  73. * See: https://github.com/jshttp/http-errors
  74. *
  75. * Note: `status` should only be passed as the first parameter.
  76. *
  77. * @param {String|Number|Error} err, msg or status
  78. * @param {String|Number|Error} [err, msg or status]
  79. * @param {Object} [props]
  80. * @api public
  81. */
  82. throw(...args) {
  83. throw createError(...args);
  84. },
  85. /**
  86. * Default error handling.
  87. *
  88. * @param {Error} err
  89. * @api private
  90. */
  91. onerror(err) {
  92. // don't do anything if there is no error.
  93. // this allows you to pass `this.onerror`
  94. // to node-style callbacks.
  95. if (null == err) return;
  96. // When dealing with cross-globals a normal `instanceof` check doesn't work properly.
  97. // See https://github.com/koajs/koa/issues/1466
  98. // We can probably remove it once jest fixes https://github.com/facebook/jest/issues/2549.
  99. const isNativeError =
  100. Object.prototype.toString.call(err) === '[object Error]' ||
  101. err instanceof Error;
  102. if (!isNativeError) err = new Error(util.format('non-error thrown: %j', err));
  103. let headerSent = false;
  104. if (this.headerSent || !this.writable) {
  105. headerSent = err.headerSent = true;
  106. }
  107. // delegate
  108. this.app.emit('error', err, this);
  109. // nothing we can do here other
  110. // than delegate to the app-level
  111. // handler and log.
  112. if (headerSent) {
  113. return;
  114. }
  115. const { res } = this;
  116. // first unset all headers
  117. /* istanbul ignore else */
  118. if (typeof res.getHeaderNames === 'function') {
  119. res.getHeaderNames().forEach(name => res.removeHeader(name));
  120. } else {
  121. res._headers = {}; // Node < 7.7
  122. }
  123. // then set those specified
  124. this.set(err.headers);
  125. // force text/plain
  126. this.type = 'text';
  127. let statusCode = err.status || err.statusCode;
  128. // ENOENT support
  129. if ('ENOENT' === err.code) statusCode = 404;
  130. // default to 500
  131. if ('number' !== typeof statusCode || !statuses[statusCode]) statusCode = 500;
  132. // respond
  133. const code = statuses[statusCode];
  134. const msg = err.expose ? err.message : code;
  135. this.status = err.status = statusCode;
  136. this.length = Buffer.byteLength(msg);
  137. res.end(msg);
  138. },
  139. get cookies() {
  140. if (!this[COOKIES]) {
  141. this[COOKIES] = new Cookies(this.req, this.res, {
  142. keys: this.app.keys,
  143. secure: this.request.secure
  144. });
  145. }
  146. return this[COOKIES];
  147. },
  148. set cookies(_cookies) {
  149. this[COOKIES] = _cookies;
  150. }
  151. };
  152. /**
  153. * Custom inspection implementation for newer Node.js versions.
  154. *
  155. * @return {Object}
  156. * @api public
  157. */
  158. /* istanbul ignore else */
  159. if (util.inspect.custom) {
  160. module.exports[util.inspect.custom] = module.exports.inspect;
  161. }
  162. /**
  163. * Response delegation.
  164. */
  165. delegate(proto, 'response')
  166. .method('attachment')
  167. .method('redirect')
  168. .method('remove')
  169. .method('vary')
  170. .method('has')
  171. .method('set')
  172. .method('append')
  173. .method('flushHeaders')
  174. .access('status')
  175. .access('message')
  176. .access('body')
  177. .access('length')
  178. .access('type')
  179. .access('lastModified')
  180. .access('etag')
  181. .getter('headerSent')
  182. .getter('writable');
  183. /**
  184. * Request delegation.
  185. */
  186. delegate(proto, 'request')
  187. .method('acceptsLanguages')
  188. .method('acceptsEncodings')
  189. .method('acceptsCharsets')
  190. .method('accepts')
  191. .method('get')
  192. .method('is')
  193. .access('querystring')
  194. .access('idempotent')
  195. .access('socket')
  196. .access('search')
  197. .access('method')
  198. .access('query')
  199. .access('path')
  200. .access('url')
  201. .access('accept')
  202. .getter('origin')
  203. .getter('href')
  204. .getter('subdomains')
  205. .getter('protocol')
  206. .getter('host')
  207. .getter('hostname')
  208. .getter('URL')
  209. .getter('header')
  210. .getter('headers')
  211. .getter('secure')
  212. .getter('stale')
  213. .getter('fresh')
  214. .getter('ips')
  215. .getter('ip');