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

96.47% Statements 82/85
84.62% Branches 22/26
95.45% Functions 21/22
96.43% Lines 81/84

    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
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    1851x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x
    1x

    1x
    17x

    17x
    17x
    17x

    17x
    17x

    17x

    2x

    2x
    1x

    1x

    1x
    1x
    1x

    1x

    2x

    5x
    4x
    3x
    3x

    7x
    3x
    3x
    1x
    1x
    1x

    1x

    2x
    1x
    1x

    2x
    2x
    1x

    1x
    1x

    3x
    2x
    1x
    1x

    1x
    1x

    18x
    18x

    18x
    18x
    1x
    1x
    1x

    17x

    19x
    19x
    18x

    18x
    18x

    18x

    1x

    1x

    1x
    1x

    17x
    17x
    17x

    17x

    1x
    1x

    1x

    1x

    1x

     import { Logger } from '@nestjs/common/services/logger.service';
    import { loadPackage } from '@nestjs/common/utils/load-package.util';
    import { isObject } from '@nestjs/common/utils/shared.utils';
    import { Observable } from 'rxjs';
    import { GRPC_DEFAULT_URL } from '../constants';
    import { InvalidGrpcPackageException } from '../exceptions/errors/invalid-grpc-package.exception';
    import { InvalidGrpcServiceException } from '../exceptions/errors/invalid-grpc-service.exception';
    import { InvalidProtoDefinitionException } from '../exceptions/errors/invalid-proto-definition.exception';
    import { ClientGrpc, GrpcOptions } from '../interfaces';
    import { ClientOptions } from '../interfaces/client-metadata.interface';
    import { ClientProxy } from './client-proxy';
    import { GRPC_CANCELLED } from './constants';

    let grpcPackage: any = {};
    let grpcProtoLoaderPackage: any = {};

    export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
      protected readonly logger = new Logger(ClientProxy.name);
      protected readonly url: string;
      protected grpcClient: any;

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

        grpcPackage = loadPackage('grpc', ClientGrpcProxy.name);
        grpcProtoLoaderPackage = loadPackage(
          '@grpc/proto-loader',
          ClientGrpcProxy.name,
        );
        this.grpcClient = this.createClient();
      }

      public getService<T extends {}>(name: string): T {
        const options: any = isObject(this.options)
          ? { ...this.options, loader: '' }
          : {};

        if (!this.grpcClient[name]) {
          throw new InvalidGrpcServiceException();
        }
        const grpcClient = new this.grpcClient[name](
          this.url,
          options.credentials || grpcPackage.credentials.createInsecure(),
          options,
        );
        const protoMethods = Object.keys(this.grpcClient[name].prototype);
        const grpcService = {} as T;
        protoMethods.forEach(m => {
          const key = m[0].toLowerCase() + m.slice(1, m.length);
          grpcService[key] = this.createServiceMethod(grpcClient, m);
        });
        return grpcService;
      }

      public createServiceMethod(
        client: any,
        methodName: string,
      ): (...args) => Observable<any> {
        return client[methodName].responseStream
          ? this.createStreamServiceMethod(client, methodName)
          : this.createUnaryServiceMethod(client, methodName);
      }

      public createStreamServiceMethod(
        client: any,
        methodName: string,
      ): (...args) => Observable<any> {
        return (...args) => {
          return new Observable(observer => {
            let isClientCanceled = false;
            const call = client[methodName](...args);

            call.on('data', (data: any) => observer.next(data));
            call.on('error', (error: any) => {
              if (error.details === GRPC_CANCELLED) {
                call.destroy();
                Eif (isClientCanceled) {
                  return;
                }
              }
              observer.error(error);
            });
            call.on('end', () => {
              call.removeAllListeners();
              observer.complete();
            });
            return () => {
              if (call.finished) {
                return undefined;
              }
              isClientCanceled = true;
              call.cancel();
            };
          });
        };
      }

      public createUnaryServiceMethod(
        client: any,
        methodName: string,
      ): (...args) => Observable<any> {
        return (...args) => {
          return new Observable(observer => {
            client[methodName](...args, (error: any, data: any) => {
              Iif (error) {
                return observer.error(error);
              }
              observer.next(data);
              observer.complete();
            });
          });
        };
      }

      public createClient(): any {
        const grpcContext = this.loadProto();
        const packageName = this.getOptionsProp<GrpcOptions>(
          this.options,
          'package',
        );
        const grpcPkg = this.lookupPackage(grpcContext, packageName);
        if (!grpcPkg) {
          const invalidPackageError = new InvalidGrpcPackageException();
          this.logger.error(invalidPackageError.message, invalidPackageError.stack);
          throw invalidPackageError;
        }
        return grpcPkg;
      }

      public loadProto(): any {
        try {
          const file = this.getOptionsProp<GrpcOptions>(this.options, 'protoPath');
          const loader = this.getOptionsProp<GrpcOptions>(this.options, 'loader');

          const packageDefinition = grpcProtoLoaderPackage.loadSync(file, loader);
          const packageObject = grpcPackage.loadPackageDefinition(
            packageDefinition,
          );
          return packageObject;
        } catch (err) {
          const invalidProtoError = new InvalidProtoDefinitionException();
          const message =
            err && err.message ? err.message : invalidProtoError.message;

          this.logger.error(message, invalidProtoError.stack);
          throw invalidProtoError;
        }
      }

      public lookupPackage(root: any, packageName: string) {
        /** Reference: https://github.com/kondi/rxjs-grpc */
        let pkg = root;
        for (const name of packageName.split(/\./)) {
          pkg = pkg[name];
        }
        return pkg;
      }

      public close() {
        this.grpcClient && this.grpcClient.close();
        this.grpcClient = null;
      }

      public async connect(): Promise<any> {
        throw new Error('The "connect()" method is not supported in gRPC mode.');
      }

      public send<TResult = any, TInput = any>(
        pattern: any,
        data: TInput,
      ): Observable<TResult> {
        throw new Error(
          'Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).',
        );
      }

      protected publish(partialPacket, callback: (packet) => any) {
        throw new Error(
          'Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).',
        );
      }
    }