node-fetch/src/response.js

96 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-04-05 10:43:12 -07:00
2015-01-27 05:11:26 -08:00
/**
* response.js
*
* Response class provides content decoding
*/
import http from 'http';
import Headers from './headers.js';
import Body, { clone } from './body';
2015-01-27 05:11:26 -08:00
const INTERNALS = Symbol('Response internals');
// fix an issue where "STATUS_CODES" aren't a named export for node <10
const STATUS_CODES = http.STATUS_CODES;
2015-01-27 05:11:26 -08:00
/**
* Response class
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
export default class Response {
constructor(body = null, opts = {}) {
Body.call(this, body, opts);
const status = opts.status || 200;
this[INTERNALS] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers: new Headers(opts.headers)
};
}
get url() {
return this[INTERNALS].url;
}
get status() {
return this[INTERNALS].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;
}
get statusText() {
return this[INTERNALS].statusText;
}
get headers() {
return this[INTERNALS].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
2018-03-04 20:29:12 -08:00
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok
});
}
2015-01-27 05:11:26 -08:00
}
2017-02-26 14:42:09 -08:00
Body.mixIn(Response.prototype);
Object.defineProperties(Response.prototype, {
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
Object.defineProperty(Response.prototype, Symbol.toStringTag, {
value: 'Response',
writable: false,
enumerable: false,
configurable: true
});