All files / microservices/server server-grpc.ts

88% Statements 66/75
75% Branches 12/16
91.3% Functions 21/23
87.5% Lines 63/72
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 1781x 1x 1x 1x 1x           1x   1x 1x   1x       19x 19x 19x     19x 19x             3x 3x       3x 3x 3x       2x 2x       2x 2x 1x 1x 1x   1x 2x               3x       3x     3x 2x     2x 1x   1x         3x       1x                   2x           3x 1x 1x 1x             4x 2x 2x 2x   3x 2x         1x 1x       2x 2x   2x         2x 2x       2x       2x                         2x 2x 2x   2x 2x     2x                      
import { fromEvent } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { CANCEL_EVENT, GRPC_DEFAULT_URL } from '../constants';
import { InvalidGrpcPackageException } from '../exceptions/errors/invalid-grpc-package.exception';
import { InvalidProtoDefinitionException } from '../exceptions/errors/invalid-proto-definition.exception';
import { CustomTransportStrategy } from '../interfaces';
import {
  GrpcOptions,
  MicroserviceOptions,
} from '../interfaces/microservice-configuration.interface';
import { Server } from './server';
 
let grpcPackage: any = {};
let grpcProtoLoaderPackage: any = {};
 
export class ServerGrpc extends Server implements CustomTransportStrategy {
  private readonly url: string;
  private grpcClient: any;
 
  constructor(private readonly options: MicroserviceOptions['options']) {
    super();
    this.url =
      this.getOptionsProp<GrpcOptions>(options, 'url') || GRPC_DEFAULT_URL;
 
    grpcPackage = this.loadPackage('grpc', ServerGrpc.name);
    grpcProtoLoaderPackage = this.loadPackage(
      '@grpc/proto-loader',
      ServerGrpc.name,
    );
  }
 
  public async listen(callback: () => void) {
    this.grpcClient = this.createClient();
    await this.start(callback);
  }
 
  public async start(callback?: () => void) {
    await this.bindEvents();
    this.grpcClient.start();
    callback();
  }
 
  public async bindEvents() {
    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;
    }
    for (const name of this.getServiceNames(grpcPkg)) {
      this.grpcClient.addService(
        grpcPkg[name].service,
        await this.createService(grpcPkg[name], name),
      );
    }
  }
 
  public getServiceNames(grpcPkg: any) {
    return Object.keys(grpcPkg).filter(name => grpcPkg[name].service);
  }
 
  public async createService(grpcService: any, name: string) {
    const service = {};
 
    // tslint:disable-next-line:forin
    for (const methodName in grpcService.prototype) {
      const methodHandler = this.messageHandlers[
        this.createPattern(name, methodName)
      ];
      if (!methodHandler) {
        continue;
      }
      service[methodName] = await this.createServiceMethod(
        methodHandler,
        grpcService.prototype[methodName],
      );
    }
    return service;
  }
 
  public createPattern(service: string, methodName: string): string {
    return JSON.stringify({
      service,
      rpc: methodName,
    });
  }
 
  public createServiceMethod(
    methodHandler: Function,
    protoNativeHandler: any,
  ): Function {
    return protoNativeHandler.responseStream
      ? this.createStreamServiceMethod(methodHandler)
      : this.createUnaryServiceMethod(methodHandler);
  }
 
  public createUnaryServiceMethod(methodHandler): Function {
    return async (call, callback) => {
      const handler = methodHandler(call.request, call.metadata);
      this.transformToObservable(await handler).subscribe(
        data => callback(null, data),
        err => callback(err),
      );
    };
  }
 
  public createStreamServiceMethod(methodHandler): Function {
    return async (call, callback) => {
      const handler = methodHandler(call.request, call.metadata);
      const result$ = this.transformToObservable(await handler);
      await result$
        .pipe(takeUntil(fromEvent(call, CANCEL_EVENT)))
        .forEach(data => call.write(data));
      call.end();
    };
  }
 
  public close() {
    this.grpcClient && this.grpcClient.forceShutdown();
    this.grpcClient = null;
  }
 
  public deserialize(obj): any {
    try {
      return JSON.parse(obj);
    } catch (e) {
      return obj;
    }
  }
 
  public createClient(): any {
    const server = new grpcPackage.Server();
    const credentials = this.getOptionsProp<GrpcOptions>(
      this.options,
      'credentials',
    );
    server.bind(
      this.url,
      credentials || grpcPackage.ServerCredentials.createInsecure(),
    );
    return server;
  }
 
  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 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;
    }
  }
}