Skip to content

Commit

Permalink
Exit process when using node (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoontek authored May 22, 2024
1 parent 6136dce commit ffbd547
Show file tree
Hide file tree
Showing 8 changed files with 1,346 additions and 1,261 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const env = validate({
// }>
```

_⚠️  In case of incorrect environment variables, the function will throw an `EnvValidationError` exposing `variables` names (not their values) to prevent your application from starting._
_⚠️  In case of incorrect environment variables, the function will either exit the process or throw an EnvValidationError, exposing the variable names (but not their values) to prevent your application from starting._

#### overrides

Expand Down
60 changes: 36 additions & 24 deletions __tests__/customValidators.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { expect, test } from "vitest";
import { EnvValidationError, Validator, validate } from "../src";
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
import { Validator, validate } from "../src";
import { Mock } from "./types";

let mockLog: Mock<typeof console.error> = undefined;
let mockExit: Mock<typeof process.exit> = undefined;

beforeAll(() => {
mockLog = vi.spyOn(console, "error").mockImplementation(() => {});
mockExit = vi.spyOn(process, "exit").mockImplementation(() => ({}) as never);
});

afterEach(() => {
mockLog?.mockReset();
mockExit?.mockReset();
});

afterAll(() => {
mockLog?.mockRestore();
mockExit?.mockRestore();
});

const nodeEnv: Validator<"development" | "test" | "production"> = (value) => {
if (value === "development" || value === "test" || value === "production") {
Expand Down Expand Up @@ -49,28 +68,21 @@ test("with invalid input", () => {
COOKIE_KEY: "invalid hex",
};

try {
validate({
env: input,
validators: {
NODE_ENV: nodeEnv,
SERVER_URL: url,
COOKIE_KEY: hex,
},
});
} catch (error) {
expect(error).toBeInstanceOf(EnvValidationError);

expect((error as EnvValidationError).message).toBe(
"Some environment variables cannot be validated: NODE_ENV, SERVER_URL, COOKIE_KEY",
);

expect((error as EnvValidationError).variables).toStrictEqual([
"NODE_ENV",
"SERVER_URL",
"COOKIE_KEY",
]);
}
validate({
env: input,
validators: {
NODE_ENV: nodeEnv,
SERVER_URL: url,
COOKIE_KEY: hex,
},
});

expect(mockLog).toHaveBeenCalledWith(
"Some environment variables cannot be validated: NODE_ENV, SERVER_URL, COOKIE_KEY",
);

expect(mockExit).toHaveBeenCalledOnce();
expect(mockExit).toHaveBeenCalledWith(1);
});

test("with invalid overrides", () => {
Expand Down
6 changes: 6 additions & 0 deletions __tests__/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { MockInstance } from "vitest";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Mock<T extends (...args: any[]) => any> =
| MockInstance<Parameters<T>, ReturnType<T>>
| undefined;
128 changes: 69 additions & 59 deletions __tests__/validate.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { expect, test } from "vitest";
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
import {
EnvValidationError,
boolean,
email,
number,
Expand All @@ -11,6 +10,25 @@ import {
url,
validate,
} from "../src";
import { Mock } from "./types";

let mockLog: Mock<typeof console.error> = undefined;
let mockExit: Mock<typeof process.exit> = undefined;

beforeAll(() => {
mockLog = vi.spyOn(console, "error").mockImplementation(() => {});
mockExit = vi.spyOn(process, "exit").mockImplementation(() => ({}) as never);
});

afterEach(() => {
mockLog?.mockReset();
mockExit?.mockReset();
});

afterAll(() => {
mockLog?.mockRestore();
mockExit?.mockRestore();
});

test("with valid input", () => {
const input = {
Expand Down Expand Up @@ -77,32 +95,25 @@ test("with invalid env variables", () => {
THUD: "john-doe.com",
};

try {
validate({
env: input,
validators: {
FOO: string,
BAR: number,
BAZ: boolean,
QUX: oneOf("a", "b"),
QUUX: url,
FRED: port,
THUD: email,
},
});
} catch (e) {
expect(e).toBeInstanceOf(EnvValidationError);
const error = e as EnvValidationError;

expect(error.variables).toStrictEqual([
"BAR",
"BAZ",
"QUX",
"QUUX",
"FRED",
"THUD",
]);
}
validate({
env: input,
validators: {
FOO: string,
BAR: number,
BAZ: boolean,
QUX: oneOf("a", "b"),
QUUX: url,
FRED: port,
THUD: email,
},
});

expect(mockLog).toHaveBeenCalledWith(
"Some environment variables cannot be validated: BAR, BAZ, QUX, QUUX, FRED, THUD",
);

expect(mockExit).toHaveBeenCalledOnce();
expect(mockExit).toHaveBeenCalledWith(1);
});

test("with missing env variables", () => {
Expand All @@ -111,20 +122,21 @@ test("with missing env variables", () => {
BAR: "", // empty strings means not set
};

try {
validate({
env: input,
validators: {
FOO: string,
BAR: string,
BAZ: boolean,
},
});
} catch (e) {
expect(e).toBeInstanceOf(EnvValidationError);
const error = e as EnvValidationError;
expect(error.variables).toStrictEqual(["BAR", "BAZ"]);
}
validate({
env: input,
validators: {
FOO: string,
BAR: string,
BAZ: boolean,
},
});

expect(mockLog).toHaveBeenCalledWith(
"Some environment variables cannot be validated: BAR, BAZ",
);

expect(mockExit).toHaveBeenCalledOnce();
expect(mockExit).toHaveBeenCalledWith(1);
});

test("with invalid and missing env variables", () => {
Expand All @@ -133,23 +145,21 @@ test("with invalid and missing env variables", () => {
BAR: "bar",
};

try {
validate({
env: input,
validators: {
FOO: string,
BAR: number,
BAZ: boolean,
},
});
} catch (error) {
expect(error).toBeInstanceOf(EnvValidationError);

expect((error as EnvValidationError).variables).toStrictEqual([
"BAR",
"BAZ",
]);
}
validate({
env: input,
validators: {
FOO: string,
BAR: number,
BAZ: boolean,
},
});

expect(mockLog).toHaveBeenCalledWith(
"Some environment variables cannot be validated: BAR, BAZ",
);

expect(mockExit).toHaveBeenCalledOnce();
expect(mockExit).toHaveBeenCalledWith(1);
});

test("with overrides", () => {
Expand Down
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "valienv",
"version": "0.6.0",
"version": "0.7.0",
"license": "MIT",
"description": "A simple environment variables validator for Node.js, web browsers and React Native",
"author": "Mathieu Acthernoene <[email protected]>",
Expand Down Expand Up @@ -46,14 +46,14 @@
]
},
"devDependencies": {
"@types/node": "^20.11.20",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"eslint": "^8.56.0",
"@types/node": "^20.12.12",
"@typescript-eslint/eslint-plugin": "^7.10.0",
"@typescript-eslint/parser": "^7.10.0",
"eslint": "^8.57.0",
"microbundle": "^0.15.1",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4",
"typescript": "^5.3.3",
"vitest": "^1.3.1"
"typescript": "^5.4.5",
"vitest": "^1.6.0"
}
}
9 changes: 8 additions & 1 deletion src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ export const validate = <
});

if (invalidVariables.length > 0) {
throw new EnvValidationError(invalidVariables);
const error = new EnvValidationError(invalidVariables);

if (typeof process === "undefined") {
throw error;
} else {
console.error(error.message);
process.exit(1);
}
}

// @ts-expect-error
Expand Down
1 change: 1 addition & 0 deletions vite.config.ts → vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["__tests__/*.ts"],
exclude: ["__tests__/types.ts"],
},
});
Loading

0 comments on commit ffbd547

Please sign in to comment.