This repository has been archived on 2023-10-27. You can view files and clone it, but cannot push or open issues or pull requests.
Files
node-fetch-cache/classes/response.js

48 lines
958 B
JavaScript
Raw Normal View History

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