All files / microservices/decorators pattern.decorator.ts

100% Statements 19/19
100% Branches 6/6
100% Functions 6/6
100% Lines 19/19
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 471x           1x     6x 6x 6x 6x                 1x 3x 3x 3x       1x           3x 2x   3x 1x 1x   2x 1x   1x    
import { PATTERN_METADATA, PATTERN_HANDLER_METADATA } from '../constants';
import { PatternMetadata } from '../interfaces/pattern-metadata.interface';
 
/**
 * Subscribes to incoming messages which fulfils chosen pattern.
 */
export const MessagePattern = <T = PatternMetadata | string>(
  metadata?: T,
): MethodDecorator => {
  return (target, key, descriptor: PropertyDescriptor) => {
    Reflect.defineMetadata(PATTERN_METADATA, metadata, descriptor.value);
    Reflect.defineMetadata(PATTERN_HANDLER_METADATA, true, descriptor.value);
    return descriptor;
  };
};
 
/**
 * Registers gRPC method handler for specified service.
 */
export function GrpcMethod(service?: string);
export function GrpcMethod(service: string, method?: string);
export function GrpcMethod(service: string, method?: string) {
  return (target, key, descriptor: PropertyDescriptor) => {
    const metadata = createMethodMetadata(target, key, service, method);
    return MessagePattern(metadata)(target, key, descriptor);
  };
}
 
export function createMethodMetadata(
  target: any,
  key: string,
  service: string | undefined,
  method: string | undefined,
) {
  const capitalizeFirstLetter = (str: string) =>
    str.charAt(0).toUpperCase() + str.slice(1);
 
  if (!service) {
    const { name } = target.constructor;
    return { service: name, rpc: capitalizeFirstLetter(key) };
  }
  if (service && !method) {
    return { service, rpc: capitalizeFirstLetter(key) };
  }
  return { service, rpc: method };
}