Another interesting trick is dispatching by file name.
In some systems, it's common not to have one file with different keys for configuration, but different files belonging to different environments. For example:
configs/
database.development.json
database.production.json
database.test.json
Somewhere in the source code must be a piece of code that selects which file to load. The code below uses dispatching by key:
import fs from 'fs';
const configFileNamesByEnv = {
development: 'database.development.json',
production: 'database.production.json',
test: 'database.test.json',
};
const filename = configFileNamesByEnv[env];
const raw = fs.readFileSync(filename);
const config = JSON.parse(raw);
It's not difficult to see that by having a startup environment name, it's possible to create a suitable file name. Let's do that:
const filename = `database.${env}.json`;
const raw = fs.readFileSync(filename);
const config = JSON.parse(raw);
The code is much shorter and no longer needs to be changed when expanding.
The Hexlet support team or other students will answer you.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.