2021-06-10 15:28:05 +00:00
|
|
|
const stream = require('stream');
|
2020-11-28 04:28:00 +00:00
|
|
|
const Headers = require('./headers.js');
|
|
|
|
|
|
|
|
class Response {
|
2021-06-11 15:25:24 +00:00
|
|
|
constructor(raw, ejectSelfFromCache, fromCache) {
|
2020-11-28 04:28:00 +00:00
|
|
|
Object.assign(this, raw);
|
2021-06-11 15:25:24 +00:00
|
|
|
this.ejectSelfFromCache = ejectSelfFromCache;
|
2020-11-28 04:28:00 +00:00
|
|
|
this.headers = new Headers(raw.headers);
|
|
|
|
this.fromCache = fromCache;
|
2021-06-10 15:28:05 +00:00
|
|
|
this.bodyUsed = false;
|
2020-11-28 04:28:00 +00:00
|
|
|
|
|
|
|
if (this.bodyBuffer.type === 'Buffer') {
|
|
|
|
this.bodyBuffer = Buffer.from(this.bodyBuffer);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-10 15:28:05 +00:00
|
|
|
get body() {
|
|
|
|
return stream.Readable.from(this.bodyBuffer);
|
|
|
|
}
|
|
|
|
|
2021-06-10 15:11:33 +00:00
|
|
|
consumeBody() {
|
2021-06-10 15:28:05 +00:00
|
|
|
if (this.bodyUsed) {
|
2021-06-10 15:11:33 +00:00
|
|
|
throw new Error('Error: body used already');
|
|
|
|
}
|
|
|
|
|
2021-06-10 15:28:05 +00:00
|
|
|
this.bodyUsed = true;
|
2021-06-10 15:11:33 +00:00
|
|
|
return this.bodyBuffer;
|
|
|
|
}
|
|
|
|
|
2021-06-11 20:37:51 +00:00
|
|
|
async text() {
|
2021-06-10 15:11:33 +00:00
|
|
|
return this.consumeBody().toString();
|
2020-11-28 04:28:00 +00:00
|
|
|
}
|
|
|
|
|
2021-06-11 20:37:51 +00:00
|
|
|
async json() {
|
2021-06-10 15:11:33 +00:00
|
|
|
return JSON.parse(this.consumeBody().toString());
|
2020-11-28 04:28:00 +00:00
|
|
|
}
|
|
|
|
|
2021-06-11 20:37:51 +00:00
|
|
|
async buffer() {
|
2021-06-10 15:11:33 +00:00
|
|
|
return this.consumeBody();
|
2020-11-28 04:28:00 +00:00
|
|
|
}
|
|
|
|
|
2021-06-11 15:25:24 +00:00
|
|
|
ejectFromCache() {
|
|
|
|
return this.ejectSelfFromCache();
|
2020-11-28 04:28:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Response;
|