UNPKG

redis-module

Version:
64 lines (63 loc) 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createAsyncClientOptions = exports.createClient = exports.RedisClientError = void 0; const tslib_1 = require("tslib"); const ioredis_1 = (0, tslib_1.__importDefault)(require("ioredis")); const uuid_1 = require("uuid"); const redis_constants_1 = require("./redis.constants"); class RedisClientError extends Error { } exports.RedisClientError = RedisClientError; function getClient(options) { return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { const { onClientReady, url } = options, opt = (0, tslib_1.__rest)(options, ["onClientReady", "url"]); let client = url ? new ioredis_1.default(url) : new ioredis_1.default(opt); client.on("error", (error) => { console.log("redis connection failed: ", error); client.quit(); client = url ? new ioredis_1.default(url) : new ioredis_1.default(opt); }); client.on("connect", () => { console.log("redis connection established"); }); if (onClientReady) { onClientReady(client); } return client; }); } const createClient = () => ({ provide: redis_constants_1.REDIS_CLIENT, useFactory: (options) => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () { const clients = new Map(); let defaultKey = (0, uuid_1.v4)(); if (Array.isArray(options)) { yield Promise.all(options.map((o) => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () { const key = o.name || defaultKey; if (clients.has(key)) { throw new RedisClientError(`${o.name || 'default'} client is exists`); } clients.set(key, yield getClient(Object.assign(Object.assign({}, o), { connectTimeout: 10000, enableAutoPipelining: true, maxLoadingRetryTime: 10000 }))); }))); } else { if (options.name && options.name.length !== 0) { defaultKey = options.name; } clients.set(defaultKey, yield getClient(Object.assign(Object.assign({}, options), { connectTimeout: 10000, enableAutoPipelining: true, maxLoadingRetryTime: 10000 }))); } return { defaultKey, clients, size: clients.size, }; }), inject: [redis_constants_1.REDIS_MODULE_OPTIONS], }); exports.createClient = createClient; const createAsyncClientOptions = (options) => ({ provide: redis_constants_1.REDIS_MODULE_OPTIONS, useFactory: options.useFactory, inject: options.inject, }); exports.createAsyncClientOptions = createAsyncClientOptions;