providers: [
{ provide: "API_KEY", useValue: "abc123" },
{ provide: PaymentGateway, useClass: process.env.NODE_ENV === "test" ? FakeGateway : StripeGateway },
{ provide: "DB", useFactory: async (cfg: ConfigService) => connect(cfg.get("DB_URL")), inject: [ConfigService] },
{ provide: "AliasedLogger", useExisting: LoggerService },
]
Each kind connects a token to something different:
useValueconnects a token to a fixed value. Use it for a constant, a config object, or a mock in tests.useClassconnects a token to a class that Nest creates. Use it to choose an implementation. For example, use a fake payment gateway in tests and the real one in production. Consumers still inject the same abstract token.useFactoryruns a function and uses its return value. The function can depend on other providers listed ininject. It can also be async: Nest waits for the promise before it creates anything that depends on it. Use it for database connections or clients built from config.useExistingcreates an alias. The new token gives you the same instance as an existing provider.
useValueis for constants, config objects and mocks.useClasschooses which implementation a token gets.useFactorycomputes the value, can be async, and lists its dependencies ininject.useExistingis an alias to an existing provider's instance.
Read more