From 5bfb3339587e736fba9445f7f7561f9478e1dc80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20D=C3=B6ring?= <simon.doering@stud.hs-bochum.de> Date: Thu, 7 Jul 2022 18:30:43 +0200 Subject: [PATCH] Add configuration through environment variables --- README.md | 2 ++ camera-server/src/config/config.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/README.md b/README.md index 905df5b..cc6cdbc 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Once the code is compiled, the server can be started with `node server.js` in th The camera server can read a path to a config file from the `CONFIG_PATH` environment variable. This config file has to be in the json format and should have [this structure](./camera-server/example-config.json). +Additionally each config key can be overwritten with an environment variable `CVH_CAMERA_CONFIG_<key>` (e.g. `CVH_CAMERA_CONFIG_cameraSlots` to overwrite the numbers of camera slots). + Below is a description of the config file's properties: * `port`: The port on which the server will listen. Defaults to `5000`. diff --git a/camera-server/src/config/config.ts b/camera-server/src/config/config.ts index c14023f..4abb248 100644 --- a/camera-server/src/config/config.ts +++ b/camera-server/src/config/config.ts @@ -84,6 +84,33 @@ if (fileContent) { } } +const ENV_CONFIG_PREFIX = 'CVH_CAMERA_CONFIG_'; +Object.keys(process.env).forEach((envKey) => { + if (envKey.startsWith(ENV_CONFIG_PREFIX)) { + const configKey = envKey.slice(ENV_CONFIG_PREFIX.length); + if (indexableConfig.hasOwnProperty(configKey)) { + const expectedType = typeof indexableConfig[configKey]; + if (expectedType === 'string') { + indexableConfig[configKey] = process.env[envKey]!; + } else if (expectedType === 'number') { + const envValue = process.env[envKey]!; + const num = parseInt(envValue); + if (!isNaN(num)) { + indexableConfig[configKey] = num; + } else { + console.log( + `Error: Config key ${configKey} from environment could not be parsed to a number` + ); + } + } + } else { + console.log( + `Error: Unknown config key ${configKey} in environment` + ); + } + } +}); + const config = indexableConfig as Config; if (config.notifyPath && !path.isAbsolute(config.notifyPath) && configPath) { config.notifyPath = path.resolve( -- GitLab