forked from skunight/nestjs-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis-client.provider.ts
60 lines (53 loc) · 1.7 KB
/
redis-client.provider.ts
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
import * as Redis from 'ioredis';
import * as uuid from 'uuid';
import { Provider } from '@nestjs/common';
import { REDIS_CLIENT, REDIS_MODULE_OPTIONS } from './redis.constants';
import { RedisModuleAsyncOptions, RedisModuleOptions } from './redis.interface';
export class RedisClientError extends Error {}
export interface RedisClient {
defaultKey: string;
clients: Map<string, Redis.Redis>;
size: number;
}
async function getClient(options: RedisModuleOptions): Promise<Redis.Redis> {
const { onClientReady, url, ...opt } = options;
const client = url ? new Redis(url) : new Redis(opt);
if (onClientReady) {
onClientReady(client)
}
return client;
}
export const createClient = (): Provider => ({
provide: REDIS_CLIENT,
useFactory: async (options: RedisModuleOptions | RedisModuleOptions[]): Promise<RedisClient> => {
const clients = new Map<string, Redis.Redis>();
let defaultKey = uuid();
if (Array.isArray(options)) {
await Promise.all(
options.map(async o => {
const key = o.name || defaultKey;
if (clients.has(key)) {
throw new RedisClientError(`${o.name || 'default'} client is exists`);
}
clients.set(key, await getClient(o));
}),
);
} else {
if (options.name && options.name.length !== 0) {
defaultKey = options.name;
}
clients.set(defaultKey, await getClient(options));
}
return {
defaultKey,
clients,
size: clients.size,
};
},
inject: [REDIS_MODULE_OPTIONS],
});
export const createAsyncClientOptions = (options: RedisModuleAsyncOptions) => ({
provide: REDIS_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject,
});