# All files / microservices/client client-redis.ts

92.42% Statements 61/66
82.76% Branches 24/29
88.24% Functions 15/17
92.19% Lines 59/64

    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
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    1701x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    1x
    2x

    2x

    2x
    2x
    2x

    2x

    5x

    3x

    4x
    4x
    4x
    4x

    2x

    2x

    2x
    2x
    2x
    2x

    2x
    2x

    2x

    2x

    5x

    1x
    1x

    6x
    1x
    1x

    5x

    4x

    1x

    3x
    3x

    3x
    3x

    3x
    1x

    2x

    5x
    5x
    4x
    4x

    4x
    4x
    4x

    4x

    4x
    2x
    2x

    1x

     import { Logger } from '@nestjs/common/services/logger.service';
    import { loadPackage } from '@nestjs/common/utils/load-package.util';
    import { fromEvent, merge, Subject, zip } from 'rxjs';
    import { share, take, tap } from 'rxjs/operators';
    import {
      CONNECT_EVENT,
      ERROR_EVENT,
      MESSAGE_EVENT,
      REDIS_DEFAULT_URL,
    } from '../constants';
    import {
      ClientOpts,
      RedisClient,
      RetryStrategyOptions,
    } from '../external/redis.interface';
    import { PacketId, ReadPacket, RedisOptions, WritePacket } from '../interfaces';
    import { ClientOptions } from '../interfaces/client-metadata.interface';
    import { ClientProxy } from './client-proxy';
    import { ECONNREFUSED } from './constants';

    let redisPackage: any = {};

    export class ClientRedis extends ClientProxy {
      protected readonly logger = new Logger(ClientProxy.name);
      protected readonly url: string;
      protected pubClient: RedisClient;
      protected subClient: RedisClient;
      protected connection: Promise<any>;
      protected isExplicitlyTerminated = false;

      constructor(protected readonly options: ClientOptions['options']) {
        super();
        this.url =
          this.getOptionsProp<RedisOptions>(options, 'url') || REDIS_DEFAULT_URL;

        redisPackage = loadPackage('redis', ClientRedis.name);
      }

      public getAckPatternName(pattern: string): string {
        return `${pattern}_ack`;
      }

      public getResPatternName(pattern: string): string {
        return `${pattern}_res`;
      }

      public close() {
        this.pubClient && this.pubClient.quit();
        this.subClient && this.subClient.quit();
        this.pubClient = this.subClient = null;
        this.isExplicitlyTerminated = true;
      }

      public connect(): Promise<any> {
        Iif (this.pubClient && this.subClient) {
          return this.connection;
        }
        const error$ = new Subject<Error>();

        this.pubClient = this.createClient(error$);
        this.subClient = this.createClient(error$);
        this.handleError(this.pubClient);
        this.handleError(this.subClient);

        const pubConnect$ = fromEvent(this.pubClient, CONNECT_EVENT);
        const subClient$ = fromEvent(this.subClient, CONNECT_EVENT);

        this.connection = merge(error$, zip(pubConnect$, subClient$))
          .pipe(
            take(1),
            tap(() =>
              this.subClient.on(MESSAGE_EVENT, this.createResponseCallback()),
            ),
            share(),
          )
          .toPromise();
        return this.connection;
      }

      public createClient(error$: Subject<Error>): RedisClient {
        return redisPackage.createClient({
          ...this.getClientOptions(error$),
          url: this.url,
        });
      }

      public handleError(client: RedisClient) {
        client.addListener(ERROR_EVENT, err => this.logger.error(err));
      }

      public getClientOptions(error$: Subject<Error>): Partial<ClientOpts> {
        const retry_strategy = options => this.createRetryStrategy(options, error$);
        return {
          retry_strategy,
        };
      }

      public createRetryStrategy(
        options: RetryStrategyOptions,
        error$: Subject<Error>,
      ): undefined | number | Error {
        if (options.error && (options.error as any).code === ECONNREFUSED) {
          error$.error(options.error);
          return options.error;
        }
        if (
          this.isExplicitlyTerminated ||
          !this.getOptionsProp<RedisOptions>(this.options, 'retryAttempts') ||
          options.attempt >
            this.getOptionsProp<RedisOptions>(this.options, 'retryAttempts')
        ) {
          return undefined;
        }
        return this.getOptionsProp<RedisOptions>(this.options, 'retryDelay') || 0;
      }

      public createResponseCallback(): Function {
        return (channel: string, buffer: string) => {
          const { err, response, isDisposed, id } = JSON.parse(
            buffer,
          ) as WritePacket & PacketId;

          const callback = this.routingMap.get(id);
          Iif (!callback) {
            return;
          }
          if (isDisposed || err) {
            return callback({
              err,
              response: null,
              isDisposed: true,
            });
          }
          callback({
            err,
            response,
          });
        };
      }

      protected publish(
        partialPacket: ReadPacket,
        callback: (packet: WritePacket) => any,
      ): Function {
        try {
          const packet = this.assignPacketId(partialPacket);
          const pattern = this.normalizePattern(partialPacket.pattern);
          const responseChannel = this.getResPatternName(pattern);

          this.routingMap.set(packet.id, callback);
          this.subClient.subscribe(responseChannel, err => {
            Iif (err) {
              return;
            }
            this.pubClient.publish(
              this.getAckPatternName(pattern),
              JSON.stringify(packet),
            );
          });

          return () => {
            this.subClient.unsubscribe(responseChannel);
            this.routingMap.delete(packet.id);
          };
        } catch (err) {
          callback({ err });
        }
      }
    }