Created
March 24, 2024 21:37
-
-
Save eduardvercaemer/ff38bf82fe8b52316577fe5d8eadf512 to your computer and use it in GitHub Desktop.
Tsyringe optional dependencies (support transformer)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
type DependencyContainer, | |
type InjectionToken, | |
container, | |
inject, | |
injectable, | |
injectWithTransform, | |
} from "tsyringe"; | |
import type Transform from "tsyringe/dist/typings/types/transform"; | |
container.register("TransientContainer", {useFactory: c => c}); | |
@injectable() | |
class Optional { | |
constructor( | |
@inject("TransientContainer") | |
private readonly container: DependencyContainer, | |
) {} | |
getOptionalValue(token: InjectionToken): unknown { | |
try { | |
return this.container.resolve(token); | |
} catch (e) { | |
return null; | |
} | |
} | |
} | |
class OptionalTransformer implements Transform<Optional, unknown> { | |
public transform(optional: Optional, token: InjectionToken): unknown { | |
return optional.getOptionalValue(token); | |
} | |
} | |
@injectable() | |
class OptionalTransformerWithTransformer<Tin, Tout> | |
implements Transform<Optional, Tout | null> | |
{ | |
constructor( | |
@inject("TransientContainer") | |
private readonly container: DependencyContainer, | |
) {} | |
public transform( | |
optional: Optional, | |
token: InjectionToken, | |
transformer: InjectionToken<Transform<Tin, Tout>>, | |
...args: any[] | |
): Tout | null { | |
const value = optional.getOptionalValue(token) as Tin | null; | |
if (value === null) { | |
return null; | |
} | |
return this.container.resolve(transformer).transform(value, ...args); | |
} | |
} | |
export function injectOptional(token: InjectionToken) { | |
return injectWithTransform(Optional, OptionalTransformer, token); | |
} | |
export function injectOptionalWithTransform<Tin, Tout>( | |
token: InjectionToken, | |
transformer: InjectionToken<Transform<Tin, Tout>>, | |
...args: any[] | |
) { | |
return injectWithTransform( | |
Optional, | |
OptionalTransformWithTransformerer, | |
token, | |
transformer, | |
...args, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment