Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

assert-injector.ts

81 lines2.5 KB

1/* eslint-disable cspell/spellchecker */
2/**
3 * The code in this file is adapted from NG Extension Platform at https://ngxtension.netlify.app.
4 *
5 * Original Author: Chau Tran
6 *
7 * NG Extension Platform is an open-source project licensed under the MIT license.
8 *
9 * For more information about the original code, see
10 * https://github.com/nartc/ngxtension-platform
11 */
12/* eslint-enable */
13​
14import {
15 Injector,
16 assertInInjectionContext,
17 inject,
18 runInInjectionContext,
19} from '@angular/core'
20​
21/**
22 * `assertInjector` extends `assertInInjectionContext` with an optional `Injector`
23 * After assertion, `assertInjector` runs the `runner` function with the guaranteed `Injector`
24 * whether it is the default `Injector` within the current **Injection Context**
25 * or the custom `Injector` that was passed in.
26 *
27 * @template {() => any} Runner - Runner is a function that can return anything
28 * @param {Function} fn - the Function to pass in `assertInInjectionContext`
29 * @param {Injector | undefined | null} injector - the optional "custom" Injector
30 * @param {Runner} runner - the runner fn
31 * @returns {ReturnType<Runner>} result - returns the result of the Runner
32 *
33 * @example
34 * ```ts
35 * function injectValue(injector?: Injector) {
36 * return assertInjector(injectValue, injector, () => 'value');
37 * }
38 *
39 * injectValue(); // string
40 * ```
41 */
42export function assertInjector<TRunner extends () => any>(
43 fn: Function,
44 injector: Injector | undefined | null,
45 runner: TRunner,
46): ReturnType<TRunner>
47/**
48 * `assertInjector` extends `assertInInjectionContext` with an optional `Injector`
49 * After assertion, `assertInjector` returns a guaranteed `Injector` whether it is the default `Injector`
50 * within the current **Injection Context** or the custom `Injector` that was passed in.
51 *
52 * @param {Function} fn - the Function to pass in `assertInInjectionContext`
53 * @param {Injector | undefined | null} injector - the optional "custom" Injector
54 * @returns Injector
55 *
56 * @example
57 * ```ts
58 * function injectDestroy(injector?: Injector) {
59 * injector = assertInjector(injectDestroy, injector);
60 *
61 * return runInInjectionContext(injector, () => {
62 * // code
63 * })
64 * }
65 * ```
66 */
67export function assertInjector(
68 fn: Function,
69 injector: Injector | undefined | null,
70): Injector
71export function assertInjector(
72 fn: Function,
73 injector: Injector | undefined | null,
74 runner?: () => any,
75) {
76 !injector && assertInInjectionContext(fn)
77 const assertedInjector = injector ?? inject(Injector)
78​
79 if (!runner) return assertedInjector
80 return runInInjectionContext(assertedInjector, runner)