factoryProvider
function in meocord/common Since 4.1.0
factoryProvider<
const P extends ProviderToken,
const I extends readonly ProviderToken[] = [],
>(provider: {
provide: P
inject?: I
useFactory: (...args: Injected<I>) => Provided<P> | Promise<Provided<P>>
}): FactoryProvider<Provided<P>>Makes a factory provider whose function is typed from its inject list and its token.
Use it in place of a plain { provide, useFactory, inject } object, which works the same at runtime but whose
function TypeScript cannot type inside a list: each parameter is what the token in its place provides, and the
function must return what provide stands for.
Parameters
| Name | Type | Description |
|---|---|---|
provider | {
provide: P
inject?: I
useFactory: (
...args: Injected<I>
) => Provided<P> | Promise<Provided<P>>
} | The token to provide, the tokens to inject, and the function that makes the value. |
provider.provide | P | |
provider.inject? | I | |
provider.useFactory | (
...args: Injected<I>
) => Provided<P> | Promise<Provided<P>> |
Returns
FactoryProvider<Provided<P>>The provider, unchanged, for @MeoCord({ providers }) or a testing module's providers.
Examples
@Service()
class Settings { readonly databaseUrl = process.env.DATABASE_URL! }
class Database { constructor(readonly url: string) {} }
export const DATABASE = createToken<Database>('Database')
@MeoCord({
controllers: [],
// settings is a Settings, and the function must return a Database
providers: [factoryProvider({ provide: DATABASE, inject: [Settings], useFactory: settings => new Database(settings.databaseUrl) })],
clientOptions: { intents: [GatewayIntentBits.Guilds] },
})
class App {}