All files / core/src/linker target.ts

100% Statements 70/70
100% Branches 3/3
100% Functions 0/0
100% Lines 70/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 93x 93x 93x 93x 1x 1x  
import { Linker } from './linker';
 
/**
 * Type helper to allow {@link Factor}ing **Target**ed constructors with
 * required arguments. Used and to be used in conjunction with the
 * {@link Target} decorator.
 *
 * @typeParam V - The **Target**ed {@link InstanceType}.
 */
export type Target<V> = new (...args: any[]) => V;
 
/**
 * Class decorator factory. Links the **Target**ed constructor to its
 * corresponding instance by applying the supplied `factoryArgs`. Employ this
 * helper to link **Target**ed constructors with required arguments. Supplying a
 * `target` constructor overrides its linked instance, if any, with the
 * constructed instance.
 *
 * @param factoryArgs - The arguments for the **Target**ed constructor.
 * @param target - An optional **Target** constructor to override.
 * @typeParam K - The **Target**ed constructor type.
 * @returns A class constructor decorator.
 *
 * @example
 * **Target** a service:
 * ```ts
 * import { Target } from '@sgrud/core';
 *
 * ⁠@Target(['default'])
 * export class Service {
 *
 *   public constructor(
 *     public readonly param: string
 *   ) {}
 *
 * }
 * ```
 *
 * @example
 * {@link Factor} a **Target**ed service:
 * ```ts
 * import { Factor, type Target } from '@sgrud/core';
 * import { Service } from './service';
 *
 * export class ServiceHandler {
 *
 *   ⁠@Factor<Target<Service>>(() => Service)
 *   public readonly service!: Service;
 *
 * }
 * ```
 *
 * @see {@link Factor}
 * @see {@link Linker}
 */
export function Target<K extends new (...args: any[]) => any>(
  factoryArgs?: ConstructorParameters<K>,
  target?: K
) {
 
  /**
   * @param constructor - The class `constructor` to be decorated.
   */
  return function(constructor: K): void {
    new Linker<K>([
      [target || constructor, new constructor(...factoryArgs || [])]
    ]);
  };
 
}