提交 a8d7ad21 authored 作者: Oleg Polyakov's avatar Oleg Polyakov

change custom error handler to custom event handler

上级 2ed76a98
......@@ -65,7 +65,9 @@ With custom error handler
```typescript
export default {
url: 'redis://:authpassword@127.0.0.1:6380/4',
errorHandler: (err, client) => {},
onClientReady: (client) => {
client.on('error', (err) => {}
)},
}
```
With multi client
......
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,33 +12,33 @@ export interface RedisClient {
size: number;
}
function getClient(options: RedisModuleOptions, key: string): Redis.Redis {
const { errorHandler, url, ...opt } = options;
async function getClient(options: RedisModuleOptions): Promise<Redis.Redis> {
const { onClientReady, url, ...opt } = options;
const client = url ? new Redis(url) : new Redis(opt);
if (errorHandler) {
client.on('error', err => errorHandler(err, client));
if (onClientReady) {
onClientReady(client)
}
return client;
}
export const createClient = () => ({
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) {
await Promise.all(
options.map(async o => {
const key = o.name || defaultKey;
if (clients.has(key)) {
throw new RedisClientError(`client ${o.name} or default client is exists`);
}
clients.set(key, getClient(o, key));
throw new RedisClientError(`${o.name || 'default'} client is exists`);
}
clients.set(key, await getClient(o));
}),
);
} else {
clients.set(defaultKey, getClient(options, defaultKey));
clients.set(defaultKey, await getClient(options));
}
return {
......
import { ModuleMetadata } from '@nestjs/common/interfaces';
import { RedisOptions } from 'ioredis';
import * as IORedis from 'ioredis';
import { Redis, RedisOptions } from 'ioredis';
export interface RedisModuleOptions extends RedisOptions {
name?: string;
url?: string;
errorHandler?(err, client: IORedis.Redis): void;
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 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论