File size: 1,413 Bytes
2f527a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { commandOptions, createClient } from "redis";
import { env } from "../config.js";
import { Store } from "./base-store.js";

export default class RedisStore extends Store {
    #client = createClient({
        url: env.redisURL,
    });
    #connected;

    constructor(name) {
        super(name);
        this.#connected = this.#client.connect();
    }

    #keyOf(key) {
        return this.id + '_' + key;
    }

    async _has(key) {
        await this.#connected;

        return this.#client.hExists(key);
    }

    async _get(key) {
        await this.#connected;

        const valueType = await this.#client.get(this.#keyOf(key) + '_t');
        const value = await this.#client.get(
            commandOptions({ returnBuffers: true }),
            this.#keyOf(key)
        );

        if (!value) {
            return null;
        }

        if (valueType === 'b')
            return value;
        else
            return JSON.parse(value);
    }

    async _set(key, val, exp_sec = -1) {
        await this.#connected;

        const options = exp_sec > 0 ? { EX: exp_sec } : undefined;

        if (val instanceof Buffer) {
            await this.#client.set(
                this.#keyOf(key) + '_t',
                'b',
                options
            );
        }

        await this.#client.set(
            this.#keyOf(key),
            val,
            options
        );
    }
}