Unverified 提交 29907003 authored 作者: ziyun.zhu's avatar ziyun.zhu 提交者: GitHub

Merge pull request #39 from polyakovoleg/custom_error_handler

feat: add custom event handler
......@@ -61,6 +61,15 @@ export default {
url: 'redis://:authpassword@127.0.0.1:6380/4',
}
```
With custom error handler
```typescript
export default {
url: 'redis://:authpassword@127.0.0.1:6380/4',
onClientReady: (client) => {
client.on('error', (err) => {}
)},
}
```
With multi client
```typescript
export default [
......
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';
......@@ -11,40 +12,35 @@ export interface RedisClient {
size: number;
}
export const createClient = () => ({
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: (options: RedisModuleOptions | RedisModuleOptions[]) => {
useFactory: async (options: RedisModuleOptions | RedisModuleOptions[]): Promise<RedisClient> => {
const clients = new Map<string, Redis.Redis>();
const defaultKey = uuid();
if (Array.isArray(options)) {
for (const o of options) {
if (o.name) {
if (clients.has(o.name)) {
throw new RedisClientError(`client ${o.name} is exists`);
}
if (o.url) {
clients.set(o.name, new Redis(o.url));
} else {
clients.set(o.name, new Redis(o));
}
} else {
if (clients.has(defaultKey)) {
throw new RedisClientError('default client is exists');
}
if (o.url) {
clients.set(defaultKey, new Redis(o.url));
} else {
clients.set(defaultKey, new Redis(o));
}
}
}
} else {
if (options.url) {
clients.set(defaultKey, new Redis(options.url));
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 {
clients.set(defaultKey, new Redis(options));
}
clients.set(defaultKey, await getClient(options));
}
return {
defaultKey,
clients,
......
import { ModuleMetadata } from '@nestjs/common/interfaces';
import { RedisOptions } from 'ioredis';
import { Redis, RedisOptions } from 'ioredis';
export interface RedisModuleOptions extends RedisOptions {
name?: string;
url?: string;
onClientReady?(client: Redis): Promise<void>;
}
export interface RedisModuleAsyncOptions
extends Pick<ModuleMetadata, 'imports'> {
export interface RedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
useFactory?: (
...args: any[]
) =>
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论