1 | import NodeCache from 'node-cache';
|
2 | import Stream from 'stream';
|
3 |
|
4 | import { HybridReadableStream as _HRS } from '@fab/sandbox-node-vm';
|
5 |
|
6 | const HybridReadableStream = _HRS;
|
7 | export 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 );
|
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 |
|
\ | No newline at end of file |