it-gorillaz / configify

NestJS Config on Steroids
MIT License
69 stars 5 forks source link

How to specify a default value? #58

Open Telokis opened 2 days ago

Telokis commented 2 days ago

I have my config provider like the following:

import { Configuration, Value } from "@itgorillaz/configify";

@Configuration()
export class DatabaseConfig {
    @Value("DATABASE_HOST")
    host: string;

    @Value("DATABASE_PORT", {
        parse(value) {
            return parseInt(value);
        },
    })
    port: string;

    @Value("DATABASE_USERNAME")
    username: string;

    @Value("DATABASE_PASSWORD")
    password: string;

    @Value("DATABASE_DATABASE")
    database: string;
}

How would I specify default values to be used when the environment variable does not exist or if it's invalid?

tommelo commented 13 hours ago

@Telokis if you control the env vars where the app is deployed you could try using the variables expansion with a default value: https://github.com/it-gorillaz/configify?tab=readme-ov-file#variables-expansion

APP_CLIENT_ID=${NON_EXISTING_ENV:-DEFAULT_ID} // --> APP_CLIENT_ID=DEFAULT_ID

Note the required :- in front of the default value.

But it may be a good idea to introduce an option to set a default value to the @Value() decorator. This would cover cases where people don't control the env vars. Something like @Value('VAR', { default: 'anything' }) should work. I'll add this idea to the backlog.

Telokis commented 10 hours ago

The main use-case I have for that is to use configuration as a way to customize sensible defaults.
For example, if I use a postgres database, the port will most likely be 5432 but maybe someone has something different. I don't want all users to specify their own specific configuration for "obvious" values like that.
And if I specify defaults for everything, the .env becomes optional which is nice for the most basic use-case of my app.

I think specifying the default to the Value decorator is the best choice.