{"size": 1659, "ext": "js", "max_stars_repo_path": "util/redis-cache.js", "max_stars_repo_name": "Giancarl021/graph-interface", "max_stars_repo_stars_event_min_datetime": "2020-07-05T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T23:50:08.000Z", "max_issues_repo_path": "util/redis-cache.js", "max_issues_repo_name": "Giancarl021/graph-interface", "max_issues_repo_issues_event_min_datetime": "2020-05-30T20:16:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-16T21:45:50.000Z", "max_forks_repo_path": "util/redis-cache.js", "max_forks_repo_name": "Giancarl021/graph-interface", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 28.1186440678, "max_line_length": 82, "alphanum_fraction": 0.5461121157}
const redis = require('redis');
const createCryptHandler = require('./crypt');
const {
    nullifyOptions
} = require('./options');
const {
    promisify
} = require('util');

module.exports = async function (options, addConnection) {
    const client = redis.createClient(nullifyOptions(options));

    try {
        await new Promise((resolve, reject) => {
            client.on('error', reject);
            client.on('ready', () => {
                addConnection(client);
                resolve();
            });
        });
    } catch (err) {
        throw new Error('Redis connection error: ' + err.message);
    }

    const getAsync = promisify(client.get).bind(client);
    const setAsync = promisify(client.set).bind(client);
    const expireAsync = promisify(client.expire).bind(client);
    const hasAsync = promisify(client.exists).bind(client);

    return async function (key) {
        const crypt = createCryptHandler(key);

        async function get() {
            if (!exists()) {
                throw new Error('Cache key does not exists');
            }
            const enc = await getAsync(key);
            const dec = crypt.decrypt(enc);
            return JSON.parse(dec);
        }

        async function set(data, expiresIn) {
            const dec = JSON.stringify(data, null, Math.floor(Math.random() * 8));
            const enc = crypt.encrypt(dec);
            await setAsync(key, enc);
            await expireAsync(key, expiresIn);
        }

        async function exists() {
            return await hasAsync(key);
        }

        return {
            get,
            set,
            exists
        }
    }
}