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

62 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-07-05 22:14:42 +00:00
import { Response } from 'node-fetch';
import { PassThrough } from 'stream';
2021-06-12 23:26:05 +00:00
2021-07-05 22:14:42 +00:00
const responseInternalSymbol = Object.getOwnPropertySymbols(new Response())[1];
2021-06-12 23:26:05 +00:00
2021-07-05 22:14:42 +00:00
export class NFCResponse extends Response {
constructor(bodyStream, metaData, ejectFromCache, fromCache) {
const stream1 = new PassThrough();
const stream2 = new PassThrough();
2021-06-12 23:26:05 +00:00
2021-07-05 22:14:42 +00:00
bodyStream.pipe(stream1);
bodyStream.pipe(stream2);
2021-06-12 23:26:05 +00:00
2021-07-05 22:14:42 +00:00
super(stream1, metaData);
this.ejectFromCache = ejectFromCache;
this.fromCache = fromCache;
this.serializationStream = stream2;
2021-06-12 23:26:05 +00:00
}
2021-07-05 22:14:42 +00:00
static fromNodeFetchResponse(res, ejectFromCache) {
const bodyStream = res.body;
const metaData = {
url: res.url,
status: res.status,
statusText: res.statusText,
headers: res.headers.raw(),
size: res.size,
timeout: res.timeout,
counter: res[responseInternalSymbol].counter,
};
return new NFCResponse(bodyStream, metaData, ejectFromCache, false);
2021-06-12 23:26:05 +00:00
}
2021-07-05 22:14:42 +00:00
static fromCachedResponse(bodyStream, rawMetaData, ejectSelfFromCache) {
if (bodyStream.readableEnded) {
throw new Error('Cache returned a body stream that has already been read to end.');
}
2021-07-05 22:14:42 +00:00
return new NFCResponse(bodyStream, rawMetaData, ejectSelfFromCache, true);
2021-06-12 23:26:05 +00:00
}
2021-07-05 22:14:42 +00:00
serialize() {
return {
bodyStream: this.serializationStream,
metaData: {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers.raw(),
size: this.size,
timeout: this.timeout,
counter: this[responseInternalSymbol].counter,
},
};
2021-06-12 23:26:05 +00:00
}
ejectFromCache() {
return this.ejectSelfFromCache();
}
}