Skip to content

Commit

Permalink
Add Env class
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Jan 18, 2025
1 parent 37b78e2 commit d0516c9
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import _ from "lodash";

export class Env {
private static environment: string | undefined = process.env.NODE_ENV;

static instance(): Env {
if (_.isUndefined(this.environment)) {
this.environment = "development";
}

return new Env();
}

set(environment?: string): Env {
Env.environment = environment;

return Env.instance();
}

get(): string {
return Env.environment!;
}

is(environment: string): boolean {
return this.get() === environment;
}
}
30 changes: 30 additions & 0 deletions tests/env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, test } from "vitest";
import { Env } from "../src/env";

describe("env", () => {
test("env correctly uses NODE_ENV", () => {
const nodeEnv = process.env.NODE_ENV!;
const env = Env.instance();

expect(env.get()).toBe(nodeEnv);
expect(env.is(nodeEnv)).toBe(true);
expect(env.is("staging")).toBe(false);
});

test("env uses the fallback to NODE_ENV", () => {
const env = Env.instance().set(undefined);

expect(env.get()).toBe("development");
expect(env.is("development")).toBe(true);
});

test("env uses the environment set to it", () => {
const env = Env.instance().set("production");

expect(env.get()).toBe("production");
expect(env.is("production")).toBe(true);

env.set("development");
expect(env.is("production")).toBe(false);
});
});

0 comments on commit d0516c9

Please sign in to comment.