From 04ae667a677804f8e2cc2b5d1a6d7dd9c3f17a8b Mon Sep 17 00:00:00 2001 From: Thomas Heartman Date: Wed, 21 Aug 2024 09:19:55 +0200 Subject: [PATCH] chore: add new parse function with tests --- src/lib/util/parseEnvVar.test.ts | 34 ++++++++++++++++++++++++++++++++ src/lib/util/parseEnvVar.ts | 19 ++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/lib/util/parseEnvVar.test.ts b/src/lib/util/parseEnvVar.test.ts index c70df3551e..6ece00916c 100644 --- a/src/lib/util/parseEnvVar.test.ts +++ b/src/lib/util/parseEnvVar.test.ts @@ -1,6 +1,7 @@ import { parseEnvVarBoolean, parseEnvVarNumber, + parseEnvVarNumberWithBounds, parseEnvVarStrings, } from './parseEnvVar'; @@ -39,3 +40,36 @@ test('parseEnvVarStringList', () => { expect(parseEnvVarStrings('a,b,c', [])).toEqual(['a', 'b', 'c']); expect(parseEnvVarStrings(' a,,,b, c , ,', [])).toEqual(['a', 'b', 'c']); }); + +describe('parseEnvVarNumberWithBounds', () => { + const parse = parseEnvVarNumberWithBounds; + test('works the same as parseEnvVarNumber', () => { + expect(parse('', { fallback: 1 })).toEqual(1); + expect(parse(' ', { fallback: 1 })).toEqual(1); + expect(parse('a', { fallback: 1 })).toEqual(1); + expect(parse('1', { fallback: 1 })).toEqual(1); + expect(parse('2', { fallback: 1 })).toEqual(2); + expect(parse('2e2', { fallback: 1 })).toEqual(2); + expect(parse('-1', { fallback: 1 })).toEqual(-1); + }); + + test('prefers options override over default value if present', () => { + expect(parse('', { fallback: 1, optionsOverride: 2 })).toEqual(2); + }); + + test('accepts 0 as options override', () => { + expect(parse('', { fallback: 1, optionsOverride: 0 })).toEqual(0); + }); + + test('prefers env var over options override', () => { + expect(parse('5', { fallback: 1, optionsOverride: 2 })).toEqual(5); + }); + + test('clamps the number to greater than or equal to the min number if provided', () => { + expect(parse('1', { fallback: 0, min: 2 })).toEqual(2); + expect(parse('', { fallback: 0, min: 2 })).toEqual(2); + expect(parse('', { fallback: 0, optionsOverride: 1, min: 2 })).toEqual( + 2, + ); + }); +}); diff --git a/src/lib/util/parseEnvVar.ts b/src/lib/util/parseEnvVar.ts index 035bf3ece0..fb4ee6581a 100644 --- a/src/lib/util/parseEnvVar.ts +++ b/src/lib/util/parseEnvVar.ts @@ -38,3 +38,22 @@ export function parseEnvVarStrings( return defaultVal; } + +type parseEnvVarNumberWithBoundsOptions = { + fallback: number; + min?: number; + optionsOverride?: number; +}; + +export function parseEnvVarNumberWithBounds( + envVar: string | undefined, + { min, fallback, optionsOverride }: parseEnvVarNumberWithBoundsOptions, +): number { + const parsed = parseEnvVarNumber(envVar, optionsOverride ?? fallback); + + if (min) { + return Math.max(min, parsed); + } + + return parsed; +}