Another interesting trick is dispatching by file name.
In some systems, it's common to have different files belonging to separate environments for configuration rather than one file. For example:
configs/
database.development.json
database.production.json
database.test.json
Somewhere in the source code must be a code block 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 is not difficult to see that using a startup environment name. So we can create a suitable file name. Let us 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.
For full access to the course you need a professional subscription.
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.