UNPKG

2.1 kBJavaScriptView Raw
1import NodeCache from 'node-cache';
2import Stream from 'stream';
3/* We need something that node-fetch Response treats as a stream */
4import { HybridReadableStream as _HRS } from '@fab/sandbox-node-vm';
5// @ts-ignore
6const HybridReadableStream = _HRS;
7export class Cache {
8 constructor() {
9 this.cache = new NodeCache();
10 }
11 async set(key, value, ttl_seconds) {
12 this.cache.set(key, await this.readAllIfStream(value), ttl_seconds || 0 /* unlimited */);
13 }
14 async setJSON(key, value, ttl_seconds) {
15 await this.set(key, JSON.stringify(value), ttl_seconds);
16 }
17 async get(key) {
18 return this.cache.get(key);
19 }
20 async getJSON(key) {
21 const val = await this.get(key);
22 return val && JSON.parse(val);
23 }
24 async getArrayBuffer(key) {
25 return this.cache.get(key);
26 }
27 async getNumber(key) {
28 return this.cache.get(key);
29 }
30 async getStream(key) {
31 const buffer = this.cache.get(key);
32 if (!buffer)
33 return undefined;
34 return new HybridReadableStream({
35 async pull(controller) {
36 controller.enqueue(buffer);
37 controller.close();
38 },
39 });
40 }
41 async readAllIfStream(value) {
42 if (typeof value.getReader === 'function') {
43 const reader = value.getReader();
44 let chunk = await reader.read();
45 let buffer = Buffer.from([]);
46 const enc = new TextEncoder();
47 while (!chunk.done) {
48 buffer = Buffer.concat([buffer, enc.encode(chunk.value)]);
49 chunk = await reader.read();
50 }
51 return buffer;
52 }
53 else if (value instanceof Stream) {
54 const chunks = [];
55 return await new Promise((resolve, reject) => {
56 value.on('data', (chunk) => chunks.push(chunk));
57 value.on('error', reject);
58 value.on('end', () => resolve(Buffer.concat(chunks)));
59 });
60 }
61 return value;
62 }
63}
64//# sourceMappingURL=cache.js.map
\No newline at end of file