Environment validator
The environment validator provider is used to validate the existence of the .env
file and its content.
It helps the developer to avoid runtime errors caused by missing environment variables.
Setup
To use the environment validator provider, you need to make sure it is registered in the configureServices()
method of the App
class.
Once registered, the provider will be available in the application through the DI Container.
protected configureServices(): void | Promise<void> {
this.provider.register(Env);
}
Method checkAll
The checkFile()
method is used to validate the existence of the .env
file and its content by checking if all the environment variables are defined.
You can define from where to call the checkAll()
method. It can be called in the postServerInitialization()
method or in any other method that you prefer.
protected postServerInitialization(): void | Promise<void> {
if (this.isDevelopment()) {
this.Provider.get(Env).checkFile(".env.development");
}
}
If the .env
file is missing or if any environment variable is not defined, the checkFile()
method will throw an error with a message indicating the missing environment variables.
[PID:26759] ERROR [env-validator-provider] Environment variable PORT is not defined.
Method get
The environment validator provider also has a method called get()
that returns the value of an environment variable. It is used to get a specific environment variable value passing its name as a parameter.
this.Provider.get(Env).get("PORT");
Using everywhere
You can use the Env
provider in any class by injecting it into the constructor of your usecase, service, provider, controller or any other class.
import { Get, controller } from "@expressots/adapter-express";
import { Env } from "@expressots/core";
@controller("/")
export class AppController {
constructor(@inject(Env) private env: Env) {}
@Get("/")
execute(): string {
console.log(this.env.get("PORT"));
return "Hello from Expressots!";
}
}
Support us ❤️
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please read our support guide.