1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | const node_cache_1 = __importDefault(require("node-cache"));
|
7 | const stream_1 = __importDefault(require("stream"));
|
8 |
|
9 | const sandbox_node_vm_1 = require("@fab/sandbox-node-vm");
|
10 |
|
11 | const HybridReadableStream = sandbox_node_vm_1.HybridReadableStream;
|
12 | class Cache {
|
13 | constructor() {
|
14 | this.cache = new node_cache_1.default();
|
15 | }
|
16 | async set(key, value, ttl_seconds) {
|
17 | this.cache.set(key, await this.readAllIfStream(value), ttl_seconds || 0 );
|
18 | }
|
19 | async setJSON(key, value, ttl_seconds) {
|
20 | await this.set(key, JSON.stringify(value), ttl_seconds);
|
21 | }
|
22 | async get(key) {
|
23 | return this.cache.get(key);
|
24 | }
|
25 | async getJSON(key) {
|
26 | const val = await this.get(key);
|
27 | return val && JSON.parse(val);
|
28 | }
|
29 | async getArrayBuffer(key) {
|
30 | return this.cache.get(key);
|
31 | }
|
32 | async getNumber(key) {
|
33 | return this.cache.get(key);
|
34 | }
|
35 | async getStream(key) {
|
36 | const buffer = this.cache.get(key);
|
37 | if (!buffer)
|
38 | return undefined;
|
39 | return new HybridReadableStream({
|
40 | async pull(controller) {
|
41 | controller.enqueue(buffer);
|
42 | controller.close();
|
43 | },
|
44 | });
|
45 | }
|
46 | async readAllIfStream(value) {
|
47 | if (typeof value.getReader === 'function') {
|
48 | const reader = value.getReader();
|
49 | let chunk = await reader.read();
|
50 | let buffer = Buffer.from([]);
|
51 | const enc = new TextEncoder();
|
52 | while (!chunk.done) {
|
53 | buffer = Buffer.concat([buffer, enc.encode(chunk.value)]);
|
54 | chunk = await reader.read();
|
55 | }
|
56 | return buffer;
|
57 | }
|
58 | else if (value instanceof stream_1.default) {
|
59 | const chunks = [];
|
60 | return await new Promise((resolve, reject) => {
|
61 | value.on('data', (chunk) => chunks.push(chunk));
|
62 | value.on('error', reject);
|
63 | value.on('end', () => resolve(Buffer.concat(chunks)));
|
64 | });
|
65 | }
|
66 | return value;
|
67 | }
|
68 | }
|
69 | exports.Cache = Cache;
|
70 |
|
\ | No newline at end of file |