You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. }
  19. this[INTERNALS] = {
  20. url: opts.url,
  21. status,
  22. statusText: opts.statusText || STATUS_CODES[status],
  23. headers,
  24. counter: opts.counter,
  25. trailer: Promise.resolve(opts.trailer || new Headers()),
  26. }
  27. }
  28. get trailer () {
  29. return this[INTERNALS].trailer
  30. }
  31. get url () {
  32. return this[INTERNALS].url || ''
  33. }
  34. get status () {
  35. return this[INTERNALS].status
  36. }
  37. get ok () {
  38. return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
  39. }
  40. get redirected () {
  41. return this[INTERNALS].counter > 0
  42. }
  43. get statusText () {
  44. return this[INTERNALS].statusText
  45. }
  46. get headers () {
  47. return this[INTERNALS].headers
  48. }
  49. clone () {
  50. return new Response(clone(this), {
  51. url: this.url,
  52. status: this.status,
  53. statusText: this.statusText,
  54. headers: this.headers,
  55. ok: this.ok,
  56. redirected: this.redirected,
  57. trailer: this.trailer,
  58. })
  59. }
  60. get [Symbol.toStringTag] () {
  61. return 'Response'
  62. }
  63. }
  64. module.exports = Response
  65. Object.defineProperties(Response.prototype, {
  66. url: { enumerable: true },
  67. status: { enumerable: true },
  68. ok: { enumerable: true },
  69. redirected: { enumerable: true },
  70. statusText: { enumerable: true },
  71. headers: { enumerable: true },
  72. clone: { enumerable: true },
  73. })