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/caching/memory_cache.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

2021-07-05 22:14:42 +00:00
import { Readable } from 'stream';
2021-07-05 18:17:21 +00:00
import { KeyTimeout } from './key_timeout.js';
2021-06-12 23:26:05 +00:00
2021-07-05 22:14:42 +00:00
function streamToBuffer(stream) {
const chunks = [];
return new Promise((resolve, reject) => {
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
stream.on('error', (err) => reject(err));
stream.on('end', () => resolve(Buffer.concat(chunks)));
});
}
2021-07-05 18:17:21 +00:00
export class MemoryCache {
2021-06-12 23:26:05 +00:00
constructor(options = {}) {
this.ttl = options.ttl;
this.keyTimeout = new KeyTimeout();
this.cache = {};
}
get(key) {
2021-07-05 22:14:42 +00:00
const cachedValue = this.cache[key];
if (cachedValue) {
return {
bodyStream: Readable.from(cachedValue.bodyBuffer),
metaData: cachedValue.metaData,
};
}
return undefined;
2021-06-12 23:26:05 +00:00
}
remove(key) {
this.keyTimeout.clearTimeout(key);
delete this.cache[key];
}
2021-07-05 22:14:42 +00:00
async set(key, bodyStream, metaData) {
const bodyBuffer = await streamToBuffer(bodyStream);
this.cache[key] = { bodyBuffer, metaData };
2021-06-12 23:26:05 +00:00
if (typeof this.ttl === 'number') {
this.keyTimeout.updateTimeout(key, this.ttl, () => this.remove(key));
}
}
2021-07-05 18:17:21 +00:00
}