DEV Community

Júnior Mendes
Júnior Mendes

Posted on

Making a dead simple configuration service with Typescript

If you're working with NodeJS applications, you probably has process.env.VARIABLE statements all around your code base. The most simple method to configure an application is installing dotenv and creating that lovely .env file on the root folder of your project.

This approach, however, has some pitfalls and is error prone. What if you don't set that process.env port? You'll probably have a default value (maybe 3000?), but you will need to run your application to discover such type of thing.

That same problem has been solved by typescript for almost anything. When you have the help of static typing, you can discover some errors a lot faster. That said, how can you use Typescript to have a type-safe way to access configurations?

Show me the code!

Take a look at that short snippet:

export class EnvironmentService<Environment> {

  public constructor(
   private readonly variables: Environment
  ) {
    // some logic to assign process.env to this.variables
    // you can use, for instance, 
    this.variables = Joi.attempt<Environment>(process.env))
  }

  public get<T>(name: keyof Environment) {
    return <T><unknown>this.variables[name];
  }
}
Enter fullscreen mode Exit fullscreen mode

In a nutshell,

  • First, you need to define an interface for you environment;
  • Then, you do pass it as a type parameter to the EnvironmentService class when instantiating a new object;
  • Finally, use something like class-validator, Joi or you library of choice to assert if the process.env object has all required variables and assign its value to the variables attribute;

After those simple steps, you can use the method get to fetch all possible environment variables with the help of typescript to guide your choice - and if you need, you can cast the value to some desired type:

Test

Conclusion

That's all folks! If you liked that simple content, don't forget to comment and share with someone you might help. Also, that's my first attempt to write something in english: if you see something wrong, just message me on Twitter (@dotmendes).

References

Top comments (0)