import { RedisClientType, createClient } from 'redis';
import { StorageInterface } from "./StorageInterface";

let client: RedisClientType;

/**
 * Implementace úložiště využívající Redis server.
 */
export default class RedisStorage implements StorageInterface {
    constructor() {
        const HOST = process.env.REDIS_HOST ?? 'localhost';
        const PORT = process.env.REDIS_PORT ?? 6379;
        client = createClient({ url: `redis://${HOST}:${PORT}` });
    }

    async initialize() {
        await client.connect();
    }

    async hasData(key: string) {
        const data = await client.json.get(key);
        return (!!data);
    }

    async getData<Type>(key: string) {
        const data = await client.json.get(key, { path: '.' });
        return data as Type;
    }

    async setData<Type>(key: string, data: Type) {
        await client.json.set(key, '.', data as any);
        await client.json.get(key);
    }
}