UNPKG

2.21 kBJavaScriptView Raw
1import { ReflectiveInjector } from '../reflective_injector';
2/**
3 * This utility function receives a spread of injectable classes
4 * and returns an array of all their dependencies. Also resolves
5 * optional dependencies.
6 *
7 * ### Important:
8 *
9 * Dynamically resolving dependencies using this function
10 * will not play nice with static analysis tools, including tree-shaking.
11 * From a static analysis perspective, any dependencies which are only resolved
12 * using this function will look as though they are not used (and will be
13 * removed by tree-shaking). This *severely* limits the usefulness of this function.
14 *
15 * ### Example:
16 *
17 * ```typescript
18 * class HTTP {}
19 * class Database {}
20 *
21 * // commenting out the decorator because the `@` symbol is spoiling
22 * // jsDoc rendering in vscode
23 * // @Injectable()
24 * class PersonService {
25 * constructor(
26 * private http: HTTP,
27 * private database: Database,
28 * ) {}
29 * }
30 *
31 * // @Injectable()
32 * class OrganizationService {
33 * constructor(
34 * private http: HTTP,
35 * private personService: PersonService,
36 * ) {}
37 * }
38 *
39 * const injector = ReflectiveInjector.resolveAndCreate(
40 * resolveDependencies(OrganizationService)
41 * );
42 *
43 * const organizationService = injector.get(OrganizationService);
44 * ```
45 */
46export function resolveDependencies() {
47 var inputs = [];
48 for (var _i = 0; _i < arguments.length; _i++) {
49 inputs[_i] = arguments[_i];
50 }
51 var deps = new Set();
52 function resolver(klass) {
53 if (deps.has(klass))
54 return;
55 deps.add(klass);
56 // resolve all dependencies of the provided class and run the `resolver()` function
57 // on their constructor functions.
58 ReflectiveInjector.resolve([klass])
59 .reduce(function (a, x) { return a.concat(x.resolvedFactories); }, [])
60 .reduce(function (a, r) { return a.concat(r.dependencies); }, [])
61 .forEach(function (d) { return resolver(d.key.token); });
62 }
63 for (var _a = 0, inputs_1 = inputs; _a < inputs_1.length; _a++) {
64 var input = inputs_1[_a];
65 resolver(input);
66 }
67 return Array.from(deps);
68}
69//# sourceMappingURL=resolve_dependencies.js.map
\No newline at end of file