Load project configuration with separate secrets
Load project for a project from the following places, whichever works first:
- Command line argument, as a JSON string
- Command line argument, as a path to a JSON/JS file
- From a file at the root of the project, or in the parent directory of the root of the project
Additionaly, it will automatically sideload a "secrets" file, for settings that should not remain in a shared configuration file.
When loading configuration from files without providing the path to the file, the following locations/names are checked:
-
-
The file extensions .js, .json, .ts, .cjs, .mjs, .cts, .mts are checked, the first one found is used.
For JavaScript/TypeScript files, the default export is expected to contain the configuration.
If there is no default export, all other exports are handled as if they were a top-level object.
Secrets file can be placed in the same location (project root or one directory above), and follow the same rules regarding file extensions.
#### Overriding default file names
For testing purpose it can be useful to override the file names locally.
If NODE_ENV is set to test, file names will be config-test. and secrets-test..
Alternatively, if KEEEX_CONFIG_SUFFIX is set, it will be appended to the base names (with no dash).
The KEEEX_CONFIG_SUFFIX option takes precedence over NODE_ENV.
In any case, the default names (without any suffix) will be used as fallback.
It is possible to load a different configuration from command line.
Passing --config will load that JSON instead of the config file.
One can also pass --config to load a different config from another file.
The same can be done for secrets with --secrets.
The loaded configuration can be obtained by calling the function loadConfig().
``typescript
import {makeProfilePredicate} from "@keeex/utils/types/record.js";
import * as projectConfig from "@keeex/projectconfig";
interface Config {
port: number;
debug: boolean;
}
const isConfig = makeProfilePredicate
port: "number";
debug: "boolean";
});
interface Secrets {
login: string;
password: string;
}
const isSecrets = makeProfilePredicate
login: "string";
password: "string";
});
const getConfig = (): Promise
projectConfig.loadConfig({
configPredicate: isConfig,
secretsPredicate: isSecrets,
});
export default getConfig();
`
In the above exemple, we define a module that export the fully-typed configuration, to be used throughout a project.
Using this module would look something like this:
`typescript
import getConfig from "./services/config.js";
const config = await getConfig();
console.log(
Port: ${config.port}
Debug: ${config.debug}
User: ${config.secrets.login}
Password: ${"*".repeat(config.secrets.password.length)});``
The loaded configuration is cached after the first call, so it is safe to recall this function multiple times from multiple places if needed.