From 1b43a5f01bf231d7f4935d62b0d7581b080f94d1 Mon Sep 17 00:00:00 2001 From: allohamora Date: Mon, 10 Apr 2023 18:12:05 +0300 Subject: [PATCH] feat: add atLeastOne to for methods --- src/env/env.manager.ts | 12 ++++++------ src/env/env.picker.ts | 5 ++++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/env/env.manager.ts b/src/env/env.manager.ts index 66572ca..61ed0a7 100644 --- a/src/env/env.manager.ts +++ b/src/env/env.manager.ts @@ -1,5 +1,5 @@ import { Manager } from 'src/utils/manager.utils.js'; -import { BaseConfig, EnvPicker } from './env.picker.js'; +import { BaseConfig, AtLeastOne, EnvPicker } from './env.picker.js'; interface Options { load?: () => C; @@ -29,7 +29,7 @@ export class EnvManager ext return value; } - private getKeyOrThrow(envRecord: Partial>): K { + private getKeyOrThrow(envRecord: AtLeastOne>): K { const key = envRecord[this.nodeEnv as E] as string | undefined; if (!key) { @@ -57,7 +57,7 @@ export class EnvManager ext return this.pick(key) as EnvPicker; } - public pickFor(envRecord: Partial>): undefined | EnvPicker { + public pickFor(envRecord: AtLeastOne>): undefined | EnvPicker { const key = envRecord[this.nodeEnv as E] as string | undefined; if (!key) { @@ -67,13 +67,13 @@ export class EnvManager ext return this.pick(key) as EnvPicker; } - public pickForOrThrow(envRecord: Partial>): EnvPicker { + public pickForOrThrow(envRecord: AtLeastOne>): EnvPicker { const key = this.getKeyOrThrow(envRecord); return this.pickOrThrow(key as K); } - public getFor(envRecord: Partial>) { + public getFor(envRecord: AtLeastOne>) { const key = envRecord[this.nodeEnv as E] as string | undefined; if (!key) { @@ -83,7 +83,7 @@ export class EnvManager ext return this.get(key as K); } - public getForOrThrow(envRecord: Partial>) { + public getForOrThrow(envRecord: AtLeastOne>) { const key = this.getKeyOrThrow(envRecord); return this.getOrThrow(key as K); diff --git a/src/env/env.picker.ts b/src/env/env.picker.ts index c2cd8dc..e2b0b15 100644 --- a/src/env/env.picker.ts +++ b/src/env/env.picker.ts @@ -12,6 +12,9 @@ type MoveOptional = T extends null export type BaseConfig = Record; +// original https://stackoverflow.com/a/59987826/15681288 +export type AtLeastOne = { [K in keyof T]: Pick }[keyof T]; + export const wrapInEnvPickers = (config: C, nodeEnv: E) => { return Object.keys(config).reduce((result, key) => { return { ...result, [key]: new EnvPicker(config[key], nodeEnv) }; @@ -27,7 +30,7 @@ export class EnvPicker { return this as unknown as EnvPicker>; } - public defaultFor(envRecord: Partial>) { + public defaultFor(envRecord: AtLeastOne>) { this.state ??= envRecord[this.nodeEnv] as S; return this;