Skip to content

Commit

Permalink
feat: add custom error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Oleg Polyakov committed Mar 10, 2020
1 parent 7bb4020 commit 2ed76a9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 24 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ export default {
url: 'redis://:[email protected]:6380/4',
}
```
With custom error handler
```typescript
export default {
url: 'redis://:[email protected]:6380/4',
errorHandler: (err, client) => {},
}
```
With multi client
```typescript
export default [
Expand Down Expand Up @@ -197,4 +204,4 @@ interface RedisOptions {
showFriendlyErrorStack?: boolean;
}
```
That's it!
That's it!
41 changes: 18 additions & 23 deletions lib/redis-client.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,35 @@ export interface RedisClient {
size: number;
}

function getClient(options: RedisModuleOptions, key: string): Redis.Redis {
const { errorHandler, url, ...opt } = options;

const client = url ? new Redis(url) : new Redis(opt);
if (errorHandler) {
client.on('error', err => errorHandler(err, client));
}

return client;
}

export const createClient = () => ({
provide: REDIS_CLIENT,
useFactory: (options: RedisModuleOptions | RedisModuleOptions[]) => {
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));
}
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));
}
} else {
if (options.url) {
clients.set(defaultKey, new Redis(options.url));
} else {
clients.set(defaultKey, new Redis(options));
}
clients.set(defaultKey, getClient(options, defaultKey));
}

return {
defaultKey,
clients,
Expand Down
2 changes: 2 additions & 0 deletions lib/redis.interface.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { ModuleMetadata } from '@nestjs/common/interfaces';
import { RedisOptions } from 'ioredis';
import * as IORedis from 'ioredis';

export interface RedisModuleOptions extends RedisOptions {
name?: string;
url?: string;
errorHandler?(err, client: IORedis.Redis): void;
}

export interface RedisModuleAsyncOptions
Expand Down

0 comments on commit 2ed76a9

Please sign in to comment.