response.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. const contentDisposition = require('content-disposition');
  6. const getType = require('cache-content-type');
  7. const onFinish = require('on-finished');
  8. const escape = require('escape-html');
  9. const typeis = require('type-is').is;
  10. const statuses = require('statuses');
  11. const destroy = require('destroy');
  12. const assert = require('assert');
  13. const extname = require('path').extname;
  14. const vary = require('vary');
  15. const only = require('only');
  16. const util = require('util');
  17. const encodeUrl = require('encodeurl');
  18. const Stream = require('stream');
  19. /**
  20. * Prototype.
  21. */
  22. module.exports = {
  23. /**
  24. * Return the request socket.
  25. *
  26. * @return {Connection}
  27. * @api public
  28. */
  29. get socket() {
  30. return this.res.socket;
  31. },
  32. /**
  33. * Return response header.
  34. *
  35. * @return {Object}
  36. * @api public
  37. */
  38. get header() {
  39. const { res } = this;
  40. return typeof res.getHeaders === 'function'
  41. ? res.getHeaders()
  42. : res._headers || {}; // Node < 7.7
  43. },
  44. /**
  45. * Return response header, alias as response.header
  46. *
  47. * @return {Object}
  48. * @api public
  49. */
  50. get headers() {
  51. return this.header;
  52. },
  53. /**
  54. * Get response status code.
  55. *
  56. * @return {Number}
  57. * @api public
  58. */
  59. get status() {
  60. return this.res.statusCode;
  61. },
  62. /**
  63. * Set response status code.
  64. *
  65. * @param {Number} code
  66. * @api public
  67. */
  68. set status(code) {
  69. if (this.headerSent) return;
  70. assert(Number.isInteger(code), 'status code must be a number');
  71. assert(code >= 100 && code <= 999, `invalid status code: ${code}`);
  72. this._explicitStatus = true;
  73. this.res.statusCode = code;
  74. if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];
  75. if (this.body && statuses.empty[code]) this.body = null;
  76. },
  77. /**
  78. * Get response status message
  79. *
  80. * @return {String}
  81. * @api public
  82. */
  83. get message() {
  84. return this.res.statusMessage || statuses[this.status];
  85. },
  86. /**
  87. * Set response status message
  88. *
  89. * @param {String} msg
  90. * @api public
  91. */
  92. set message(msg) {
  93. this.res.statusMessage = msg;
  94. },
  95. /**
  96. * Get response body.
  97. *
  98. * @return {Mixed}
  99. * @api public
  100. */
  101. get body() {
  102. return this._body;
  103. },
  104. /**
  105. * Set response body.
  106. *
  107. * @param {String|Buffer|Object|Stream} val
  108. * @api public
  109. */
  110. set body(val) {
  111. const original = this._body;
  112. this._body = val;
  113. // no content
  114. if (null == val) {
  115. if (!statuses.empty[this.status]) this.status = 204;
  116. if (val === null) this._explicitNullBody = true;
  117. this.remove('Content-Type');
  118. this.remove('Content-Length');
  119. this.remove('Transfer-Encoding');
  120. return;
  121. }
  122. // set the status
  123. if (!this._explicitStatus) this.status = 200;
  124. // set the content-type only if not yet set
  125. const setType = !this.has('Content-Type');
  126. // string
  127. if ('string' === typeof val) {
  128. if (setType) this.type = /^\s*</.test(val) ? 'html' : 'text';
  129. this.length = Buffer.byteLength(val);
  130. return;
  131. }
  132. // buffer
  133. if (Buffer.isBuffer(val)) {
  134. if (setType) this.type = 'bin';
  135. this.length = val.length;
  136. return;
  137. }
  138. // stream
  139. if (val instanceof Stream) {
  140. onFinish(this.res, destroy.bind(null, val));
  141. if (original != val) {
  142. val.once('error', err => this.ctx.onerror(err));
  143. // overwriting
  144. if (null != original) this.remove('Content-Length');
  145. }
  146. if (setType) this.type = 'bin';
  147. return;
  148. }
  149. // json
  150. this.remove('Content-Length');
  151. this.type = 'json';
  152. },
  153. /**
  154. * Set Content-Length field to `n`.
  155. *
  156. * @param {Number} n
  157. * @api public
  158. */
  159. set length(n) {
  160. this.set('Content-Length', n);
  161. },
  162. /**
  163. * Return parsed response Content-Length when present.
  164. *
  165. * @return {Number}
  166. * @api public
  167. */
  168. get length() {
  169. if (this.has('Content-Length')) {
  170. return parseInt(this.get('Content-Length'), 10) || 0;
  171. }
  172. const { body } = this;
  173. if (!body || body instanceof Stream) return undefined;
  174. if ('string' === typeof body) return Buffer.byteLength(body);
  175. if (Buffer.isBuffer(body)) return body.length;
  176. return Buffer.byteLength(JSON.stringify(body));
  177. },
  178. /**
  179. * Check if a header has been written to the socket.
  180. *
  181. * @return {Boolean}
  182. * @api public
  183. */
  184. get headerSent() {
  185. return this.res.headersSent;
  186. },
  187. /**
  188. * Vary on `field`.
  189. *
  190. * @param {String} field
  191. * @api public
  192. */
  193. vary(field) {
  194. if (this.headerSent) return;
  195. vary(this.res, field);
  196. },
  197. /**
  198. * Perform a 302 redirect to `url`.
  199. *
  200. * The string "back" is special-cased
  201. * to provide Referrer support, when Referrer
  202. * is not present `alt` or "/" is used.
  203. *
  204. * Examples:
  205. *
  206. * this.redirect('back');
  207. * this.redirect('back', '/index.html');
  208. * this.redirect('/login');
  209. * this.redirect('http://google.com');
  210. *
  211. * @param {String} url
  212. * @param {String} [alt]
  213. * @api public
  214. */
  215. redirect(url, alt) {
  216. // location
  217. if ('back' === url) url = this.ctx.get('Referrer') || alt || '/';
  218. this.set('Location', encodeUrl(url));
  219. // status
  220. if (!statuses.redirect[this.status]) this.status = 302;
  221. // html
  222. if (this.ctx.accepts('html')) {
  223. url = escape(url);
  224. this.type = 'text/html; charset=utf-8';
  225. this.body = `Redirecting to <a href="${url}">${url}</a>.`;
  226. return;
  227. }
  228. // text
  229. this.type = 'text/plain; charset=utf-8';
  230. this.body = `Redirecting to ${url}.`;
  231. },
  232. /**
  233. * Set Content-Disposition header to "attachment" with optional `filename`.
  234. *
  235. * @param {String} filename
  236. * @api public
  237. */
  238. attachment(filename, options) {
  239. if (filename) this.type = extname(filename);
  240. this.set('Content-Disposition', contentDisposition(filename, options));
  241. },
  242. /**
  243. * Set Content-Type response header with `type` through `mime.lookup()`
  244. * when it does not contain a charset.
  245. *
  246. * Examples:
  247. *
  248. * this.type = '.html';
  249. * this.type = 'html';
  250. * this.type = 'json';
  251. * this.type = 'application/json';
  252. * this.type = 'png';
  253. *
  254. * @param {String} type
  255. * @api public
  256. */
  257. set type(type) {
  258. type = getType(type);
  259. if (type) {
  260. this.set('Content-Type', type);
  261. } else {
  262. this.remove('Content-Type');
  263. }
  264. },
  265. /**
  266. * Set the Last-Modified date using a string or a Date.
  267. *
  268. * this.response.lastModified = new Date();
  269. * this.response.lastModified = '2013-09-13';
  270. *
  271. * @param {String|Date} type
  272. * @api public
  273. */
  274. set lastModified(val) {
  275. if ('string' === typeof val) val = new Date(val);
  276. this.set('Last-Modified', val.toUTCString());
  277. },
  278. /**
  279. * Get the Last-Modified date in Date form, if it exists.
  280. *
  281. * @return {Date}
  282. * @api public
  283. */
  284. get lastModified() {
  285. const date = this.get('last-modified');
  286. if (date) return new Date(date);
  287. },
  288. /**
  289. * Set the ETag of a response.
  290. * This will normalize the quotes if necessary.
  291. *
  292. * this.response.etag = 'md5hashsum';
  293. * this.response.etag = '"md5hashsum"';
  294. * this.response.etag = 'W/"123456789"';
  295. *
  296. * @param {String} etag
  297. * @api public
  298. */
  299. set etag(val) {
  300. if (!/^(W\/)?"/.test(val)) val = `"${val}"`;
  301. this.set('ETag', val);
  302. },
  303. /**
  304. * Get the ETag of a response.
  305. *
  306. * @return {String}
  307. * @api public
  308. */
  309. get etag() {
  310. return this.get('ETag');
  311. },
  312. /**
  313. * Return the response mime type void of
  314. * parameters such as "charset".
  315. *
  316. * @return {String}
  317. * @api public
  318. */
  319. get type() {
  320. const type = this.get('Content-Type');
  321. if (!type) return '';
  322. return type.split(';', 1)[0];
  323. },
  324. /**
  325. * Check whether the response is one of the listed types.
  326. * Pretty much the same as `this.request.is()`.
  327. *
  328. * @param {String|String[]} [type]
  329. * @param {String[]} [types]
  330. * @return {String|false}
  331. * @api public
  332. */
  333. is(type, ...types) {
  334. return typeis(this.type, type, ...types);
  335. },
  336. /**
  337. * Return response header.
  338. *
  339. * Examples:
  340. *
  341. * this.get('Content-Type');
  342. * // => "text/plain"
  343. *
  344. * this.get('content-type');
  345. * // => "text/plain"
  346. *
  347. * @param {String} field
  348. * @return {String}
  349. * @api public
  350. */
  351. get(field) {
  352. return this.header[field.toLowerCase()] || '';
  353. },
  354. /**
  355. * Returns true if the header identified by name is currently set in the outgoing headers.
  356. * The header name matching is case-insensitive.
  357. *
  358. * Examples:
  359. *
  360. * this.has('Content-Type');
  361. * // => true
  362. *
  363. * this.get('content-type');
  364. * // => true
  365. *
  366. * @param {String} field
  367. * @return {boolean}
  368. * @api public
  369. */
  370. has(field) {
  371. return typeof this.res.hasHeader === 'function'
  372. ? this.res.hasHeader(field)
  373. // Node < 7.7
  374. : field.toLowerCase() in this.headers;
  375. },
  376. /**
  377. * Set header `field` to `val`, or pass
  378. * an object of header fields.
  379. *
  380. * Examples:
  381. *
  382. * this.set('Foo', ['bar', 'baz']);
  383. * this.set('Accept', 'application/json');
  384. * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
  385. *
  386. * @param {String|Object|Array} field
  387. * @param {String} val
  388. * @api public
  389. */
  390. set(field, val) {
  391. if (this.headerSent) return;
  392. if (2 === arguments.length) {
  393. if (Array.isArray(val)) val = val.map(v => typeof v === 'string' ? v : String(v));
  394. else if (typeof val !== 'string') val = String(val);
  395. this.res.setHeader(field, val);
  396. } else {
  397. for (const key in field) {
  398. this.set(key, field[key]);
  399. }
  400. }
  401. },
  402. /**
  403. * Append additional header `field` with value `val`.
  404. *
  405. * Examples:
  406. *
  407. * ```
  408. * this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
  409. * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
  410. * this.append('Warning', '199 Miscellaneous warning');
  411. * ```
  412. *
  413. * @param {String} field
  414. * @param {String|Array} val
  415. * @api public
  416. */
  417. append(field, val) {
  418. const prev = this.get(field);
  419. if (prev) {
  420. val = Array.isArray(prev)
  421. ? prev.concat(val)
  422. : [prev].concat(val);
  423. }
  424. return this.set(field, val);
  425. },
  426. /**
  427. * Remove header `field`.
  428. *
  429. * @param {String} name
  430. * @api public
  431. */
  432. remove(field) {
  433. if (this.headerSent) return;
  434. this.res.removeHeader(field);
  435. },
  436. /**
  437. * Checks if the request is writable.
  438. * Tests for the existence of the socket
  439. * as node sometimes does not set it.
  440. *
  441. * @return {Boolean}
  442. * @api private
  443. */
  444. get writable() {
  445. // can't write any more after response finished
  446. // response.writableEnded is available since Node > 12.9
  447. // https://nodejs.org/api/http.html#http_response_writableended
  448. // response.finished is undocumented feature of previous Node versions
  449. // https://stackoverflow.com/questions/16254385/undocumented-response-finished-in-node-js
  450. if (this.res.writableEnded || this.res.finished) return false;
  451. const socket = this.res.socket;
  452. // There are already pending outgoing res, but still writable
  453. // https://github.com/nodejs/node/blob/v4.4.7/lib/_http_server.js#L486
  454. if (!socket) return true;
  455. return socket.writable;
  456. },
  457. /**
  458. * Inspect implementation.
  459. *
  460. * @return {Object}
  461. * @api public
  462. */
  463. inspect() {
  464. if (!this.res) return;
  465. const o = this.toJSON();
  466. o.body = this.body;
  467. return o;
  468. },
  469. /**
  470. * Return JSON representation.
  471. *
  472. * @return {Object}
  473. * @api public
  474. */
  475. toJSON() {
  476. return only(this, [
  477. 'status',
  478. 'message',
  479. 'header'
  480. ]);
  481. },
  482. /**
  483. * Flush any set headers, and begin the body
  484. */
  485. flushHeaders() {
  486. this.res.flushHeaders();
  487. }
  488. };
  489. /**
  490. * Custom inspection implementation for node 6+.
  491. *
  492. * @return {Object}
  493. * @api public
  494. */
  495. /* istanbul ignore else */
  496. if (util.inspect.custom) {
  497. module.exports[util.inspect.custom] = module.exports.inspect;
  498. }