response.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict'
  2. const http = require('http')
  3. const { STATUS_CODES } = http
  4. const Headers = require('./headers.js')
  5. const Body = require('./body.js')
  6. const { clone, extractContentType } = Body
  7. const INTERNALS = Symbol('Response internals')
  8. class Response extends Body {
  9. constructor (body = null, opts = {}) {
  10. super(body, opts)
  11. const status = opts.status || 200
  12. const headers = new Headers(opts.headers)
  13. if (body !== null && body !== undefined && !headers.has('Content-Type')) {
  14. const contentType = extractContentType(body)
  15. if (contentType)
  16. headers.append('Content-Type', contentType)
  17. }
  18. this[INTERNALS] = {
  19. url: opts.url,
  20. status,
  21. statusText: opts.statusText || STATUS_CODES[status],
  22. headers,
  23. counter: opts.counter,
  24. trailer: Promise.resolve(opts.trailer || new Headers()),
  25. }
  26. }
  27. get trailer () {
  28. return this[INTERNALS].trailer
  29. }
  30. get url () {
  31. return this[INTERNALS].url || ''
  32. }
  33. get status () {
  34. return this[INTERNALS].status
  35. }
  36. get ok () {
  37. return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
  38. }
  39. get redirected () {
  40. return this[INTERNALS].counter > 0
  41. }
  42. get statusText () {
  43. return this[INTERNALS].statusText
  44. }
  45. get headers () {
  46. return this[INTERNALS].headers
  47. }
  48. clone () {
  49. return new Response(clone(this), {
  50. url: this.url,
  51. status: this.status,
  52. statusText: this.statusText,
  53. headers: this.headers,
  54. ok: this.ok,
  55. redirected: this.redirected,
  56. trailer: this.trailer,
  57. })
  58. }
  59. get [Symbol.toStringTag] () {
  60. return 'Response'
  61. }
  62. }
  63. module.exports = Response
  64. Object.defineProperties(Response.prototype, {
  65. url: { enumerable: true },
  66. status: { enumerable: true },
  67. ok: { enumerable: true },
  68. redirected: { enumerable: true },
  69. statusText: { enumerable: true },
  70. headers: { enumerable: true },
  71. clone: { enumerable: true },
  72. })