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.
node-fetch-cache/classes/response.js

50 lines
965 B
JavaScript
Raw Normal View History

2020-11-28 04:28:00 +00:00
const fs = require('fs');
const Headers = require('./headers.js');
class Response {
constructor(raw, cacheFilePath, fromCache) {
Object.assign(this, raw);
this.cacheFilePath = cacheFilePath;
this.headers = new Headers(raw.headers);
this.fromCache = fromCache;
this.consumed = false;
2020-11-28 04:28:00 +00:00
if (this.bodyBuffer.type === 'Buffer') {
this.bodyBuffer = Buffer.from(this.bodyBuffer);
}
}
consumeBody() {
if (this.consumed) {
throw new Error('Error: body used already');
}
this.consumed = true;
return this.bodyBuffer;
}
2020-11-28 04:28:00 +00:00
text() {
return this.consumeBody().toString();
2020-11-28 04:28:00 +00:00
}
json() {
return JSON.parse(this.consumeBody().toString());
2020-11-28 04:28:00 +00:00
}
buffer() {
return this.consumeBody();
2020-11-28 04:28:00 +00:00
}
async ejectFromCache() {
try {
await fs.promises.unlink(this.cacheFilePath);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
2020-11-28 04:28:00 +00:00
}
}
module.exports = Response;