nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.69k stars 7.63k forks source link

Support configuration injection like Spring #2464

Closed caiorcferreira closed 5 years ago

caiorcferreira commented 5 years ago

Feature Request

Is your feature request related to a problem? Please describe.

In the Configuration technique page it's suggested to create a ConfigService/ConfigModule. Although this is a good a approach, it fills the class with a dependency larger than it need and forces one to write a stub or mock in the tests, which is more verbose than other the Spring approach. Futhermore, in order to have a type safe value, one would need to create a method in the ConfigServer for each key/value.

Describe the solution you'd like

In Spring, if I wanted to inject a configuration value in my class, I would simply:

@Service
public class MyClass {
  private String configValue;

  public MyClass(@Value("some.config.key") String configValue) {
    this.configValue = configValue;
  }
}

This way the class only knows about the value it depends on, not a complex structure like another Service, in test it would the case of only passing a String stub and it would provide a type safe value. Even though I don't know if this type safety could be achieved in Javascript runtime.

Teachability, Documentation, Adoption, Migration Strategy

Probably this feature would need a change in the dependency injection container in Nest in order to evaluate every dependency as a Value or an Injectable one. To retrive the value asked probably the framework would have a ConfigService interface (like the LoggerService interface) that the application should implement and register, and in the instance creation Nest would use it to get the value asked.

What is the motivation / use case for changing the behavior?

Reduce class coupling and ease test implementation.

If I can help developing this please let me know!

kamilmysliwiec commented 5 years ago

You can actually do it now. Simply transform your configuration object to a list of providers. As their injection tokens, use property paths and register them using custom providers (with useValue).

BrunnerLivio commented 5 years ago

Maybe nestjs-community/nestjs-config would also suit your case.

lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.