Skip to content

Commit

Permalink
feat: Cast booleans
Browse files Browse the repository at this point in the history
Converts strings true/false, True/False, TRUE/FALSE, 1/0 to boolean if the default is boolean.
  • Loading branch information
alecperkins committed Mar 29, 2023
1 parent 8791182 commit a00c0b0
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ const conf: (
_override = Number(override);
break;
}
case "boolean": {
if (override.toLowerCase() === "true") {
_override = true;
} else if (override.toLowerCase() === "false") {
_override = false;
} else if (override === "1") {
_override = true;
} else if (override === "0") {
_override = false;
} else {
_override = Boolean(override);
}
break;
}
default: {
_override = override;
}
Expand Down
42 changes: 42 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,48 @@ describe("conf", () => {
reset();
});

test("doesn't convert numbers when not originally boolean", async () => {
const reset = overrideEnv({ MYVAL: "2" });
const config = conf({ MYVAL: "asdf" });
expect(config.MYVAL).not.toEqual(2);
reset();
});

test("doesn't convert booleans when not originally boolean", async () => {
const reset = overrideEnv({ MYVAL: "true" });
const config = conf({ MYVAL: "asdf" });
expect(config.MYVAL).not.toEqual(true);
reset();
});

test("casts json booleans", async () => {
const reset = overrideEnv({ MYVAL: "true" });
const config = conf({ MYVAL: false });
expect(config.MYVAL).toEqual(true);
reset();
});

test("casts capitalized booleans", async () => {
const reset = overrideEnv({ MYVAL: "True" });
const config = conf({ MYVAL: false });
expect(config.MYVAL).toEqual(true);
reset();
});

test("casts 0 booleans", async () => {
const reset = overrideEnv({ MYVAL: "0" });
const config = conf({ MYVAL: true });
expect(config.MYVAL).toEqual(false);
reset();
});

test("casts 1 booleans", async () => {
const reset = overrideEnv({ MYVAL: "1" });
const config = conf({ MYVAL: false });
expect(config.MYVAL).toEqual(true);
reset();
});

test("reads from environment", async () => {
const reset = overrideEnv({ MYVAL: "different" });
const config = conf({ MYVAL: "testing" });
Expand Down

0 comments on commit a00c0b0

Please sign in to comment.