All files injects.ts

100% Statements 26/26
100% Branches 8/8
100% Functions 6/6
100% Lines 25/25
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    1x             1x                       1x   16x 4x 3x 3x   12x 12x 12x   15x                       1x   9x 3x   6x 6x 6x 1x     9x                     1x 34x                   1x 13x               1x 1x    
 
// tag::import[]
import * as assert from 'assert';
// end::import[]
 
// tag::injectables[]
/**
 * All injectables.
 */
export let injectables: { [k: string]: any; } = {};
// end::injectables[]
 
 
// tag::Injectable[]
/**
 * Register an injectable.
 * Can be used as a class decorator or as a function.
 *
 * @param constructorOrKey class constructor or custom string key
 * @param instance custom instance to register (optional with class constructor, mandatory with string key)
 */
export function Injectable(constructorOrKey: Function | string, instance?: any): void {
  let key: string, injectable: any;
  if (typeof constructorOrKey === 'string') {
    assert.equal(true, !!(instance), 'can\'t define injectable without instance');
    key = constructorOrKey;
    injectable = instance
  } else {
    const constructor: Function = constructorOrKey;
    key = constructor.name;
    injectable = instance ? instance : new (Object.create(constructor.prototype)).constructor();
  }
  injectables[key] = injectable;
}
// end::Injectable[]
 
// tag::inject[]
/**
 * Inject unique instance associated with class name or with custom string key.
 * Create unique class instance if it doesn't exist.
 *
 * @param constructorOrKey class constructor or custom string key
 * @return the unique instance associated with class name or with custom string key
 */
export function inject(constructorOrKey: Function | string): any {
  let key: string;
  if (typeof constructorOrKey === 'string') {
    key = constructorOrKey; // <1>
  } else {
    const constructor: Function = constructorOrKey;
    key = constructor.name; // <2>
    if (!exists(key)) {
      Injectable(constructor); // <3>
    }
  }
  return injectables[key]; // <4>
}
// end::inject[]
 
// tag::exists[]
/**
 * In order to know if a dependency exists or not.
 *
 * @param name dependency name
 * @returns true if dependency exist, false otherwise
 */
export function exists(name: string) {
  return Object.keys(injectables).some(k => k === name);
}
// end::exists[]
 
// Only for tests
 
// tag::resetInjectables[]
/**
 * Only for tests : delete all injectables
 */
export function resetInjectables() {
  injectables = {};
}
// end::resetInjectables[]
 
// tag::resetInjectable[]
/**
 * Only for tests : delete an injectable
 */
export function resetInjectable(name: string) {
  delete injectables[name];
}
// end::resetInjectable[]