Skip to content

feat(node-config-provider): add utility booleanSelector #2941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/node-config-provider/src/booleanSelector.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { booleanSelector, SelectorType } from "./booleanSelector";

describe(booleanSelector.name, () => {
const key = "key";
const obj: { [key]: any } = {} as any;

describe.each(Object.entries(SelectorType))(`Selector %s`, (selectorKey, selectorValue) => {
beforeEach(() => {
delete obj[key];
});

it(`should return undefined if ${key} is not defined`, () => {
expect(booleanSelector(obj, key, SelectorType[selectorKey])).toBeUndefined();
});

it.each([
[true, "true"],
[false, "false"],
])(`should return boolean %s if ${key}="%s"`, (output, input) => {
obj[key] = input;
expect(booleanSelector(obj, key, SelectorType[selectorKey])).toBe(output);
});

it.each(["0", "1", "yes", "no", undefined, null, void 0, ""])(`should throw if ${key}=%s`, (input) => {
obj[key] = input;
expect(() => booleanSelector(obj, key, SelectorType[selectorKey])).toThrow(
`Cannot load ${selectorValue} "${key}". Expected "true" or "false", got ${obj[key]}.`
);
});
});
});
19 changes: 19 additions & 0 deletions packages/node-config-provider/src/booleanSelector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export enum SelectorType {
ENV = "env",
CONFIG = "shared config entry",
}

/**
* Returns boolean value true/false for string value "true"/"false",
* if the string is defined in obj[key]
* Returns undefined, if obj[key] is not defined.
* Throws error for all other cases.
*
* @internal
*/
export const booleanSelector = (obj: { [key: string]: string }, key: string, type: SelectorType) => {
if (!(key in obj)) return undefined;
if (obj[key] === "true") return true;
if (obj[key] === "false") return false;
throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
};
1 change: 1 addition & 0 deletions packages/node-config-provider/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./booleanSelector";
export * from "./configLoader";