Namespaced Config & Hooks — Series 2

Preview — 3 of 10 questions

What do databaseConfig.KEY and ConfigType provide?

javascript
export default registerAs('database', () => ({
  url: process.env.DATABASE_URL,
  poolSize: parseInt(process.env.DB_POOL_SIZE ?? '10', 10),
}));

@Injectable()
export class CatsRepository {
  constructor(
    @Inject(databaseConfig.KEY)
    private readonly config: ConfigType<typeof databaseConfig>,
  ) {}
}
AThey register the namespace globally, removing the need to load it in forRoot
BKEY is the injection token registerAs attaches to the factory, and ConfigType infers the factory's return type — so the consumer receives a fully typed object and a typo in a property name is a compile error rather than an undefined at runtime
CThey validate the namespace's values against a schema at injection time
DThey make the configuration reload whenever the underlying environment changes

What do these two options change?

javascript
ConfigModule.forRoot({
  validationSchema: Joi.object({ PORT: Joi.number().default(3000), DATABASE_URL: Joi.string().uri().required() }),
  validationOptions: { allowUnknown: true, abortEarly: false },
});
AallowUnknown: true skips validation entirely, and abortEarly: false re-runs it on every read
BallowUnknown controls whether defaults are applied, and abortEarly whether the process exits on failure
CThey are Joi-specific and ignored when using a custom validate function — which is the recommended approach
DallowUnknown: true lets variables absent from the schema pass through (essential, since the environment always contains PATH, HOME and countless others), and abortEarly: false collects every validation error instead of stopping at the first — so a misconfigured deployment reports all its problems at once

Why is failing at startup preferable to handling the missing value later?

javascript
Error: Config validation error: "DATABASE_URL" is required
ABecause the failure is immediate, total and legible — the deployment fails before the instance is marked healthy and receives traffic, instead of every request failing later with an obscure driver error
BBecause Node cannot recover from an undefined environment variable
CBecause the ConfigModule cannot report errors after initialisation
DBecause orchestrators restart only processes that exit during startup

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.