diff --git a/README.md b/README.md index ed9e558..3a4585f 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,10 @@ Once the class is instantiated, you can leverage the following `ConfigScope` met * `getOptionalBoolean()`, returns the value of an optional configuration parameter and validates that it is a boolean. It the value is missing, it is assigned the `defaultValue`. If it is not a boolean, an `InternalError` is thrown. Parameters are: * `param`, the configuration parameter name; * `defaultValue`. +* `getOptionalOneOf()`, returns the value of an optional configuration parameter, if the value is missing, it falls back to the specified default value, and validates that it is one of the supported values. If the value is not supported, an `InternalError` is thrown. Parameters are: + * `param`, the configuration parameter name; + * `defaultValue` + * `supportedValues`; ### Environment Configuration Parameter diff --git a/src/config/ConfigScope.spec.ts b/src/config/ConfigScope.spec.ts index 0e8a6bb..fd617a3 100644 --- a/src/config/ConfigScope.spec.ts +++ b/src/config/ConfigScope.spec.ts @@ -228,6 +228,44 @@ describe('ConfigScope', () => { }) }) + describe('getOptionalOneOf', () => { + it('returns env value if it exists on the list', () => { + process.env.value = 'g' + const configScope = new ConfigScope() + + const resolvedValue = configScope.getOptionalOneOf('value', 'default', ['a', 'g', 'b']) + + expect(resolvedValue).toBe('g') + }) + + it('returns default if env value not exists and the default one exists on the list', () => { + delete process.env.value + const configScope = new ConfigScope() + + const resolvedValue = configScope.getOptionalOneOf('value', 'g', ['a', 'g', 'b']) + + expect(resolvedValue).toBe('g') + }) + + it('throws an error on env value item not from list', () => { + process.env.value = 'c' + const configScope = new ConfigScope() + + expect(() => configScope.getOptionalOneOf('value', 'default', ['a', 'g', 'b'])).toThrow( + /Unsupported value/, + ) + }) + + it('throws an error if env value not exists and the default one not exists on the list', () => { + delete process.env.value + const configScope = new ConfigScope() + + expect(() => configScope.getOptionalOneOf('value', 'default', ['a'])).toThrow( + /Unsupported value/, + ) + }) + }) + describe('getOptionalInteger', () => { it('accepts value', () => { process.env.value = '3' diff --git a/src/config/ConfigScope.ts b/src/config/ConfigScope.ts index e99ad78..8d19ca6 100644 --- a/src/config/ConfigScope.ts +++ b/src/config/ConfigScope.ts @@ -100,6 +100,19 @@ export class ConfigScope { ) } + getOptionalOneOf( + param: string, + defaultValue: T, + supportedValues: T[], + ): T { + const result = this.getOptional(param, defaultValue) + return validateOneOf( + result, + supportedValues, + `Unsupported ${param}: ${result}. Supported values: ${supportedValues.toString()}`, + ) + } + getOptionalValidated( param: string, defaultValue: string,