Skip to content
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

Add multiple environment support and cleanup #11

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
fix: format environment variables validation errors
  • Loading branch information
hassancodess committed Sep 13, 2024
commit 351357945d4f1b956383b3ba13c0ba4dcff4d8bf
28 changes: 25 additions & 3 deletions src/config/config.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import dotenvx from '@dotenvx/dotenvx';
import { z } from 'zod';
import { z, ZodError } from 'zod';

dotenvx.config();

const prettyPrintErrors = (errObj: ZodError) => {
const formattedError = errObj.format();
Object.entries(formattedError).forEach(([key, value]) => {
if (key !== '_errors') {
console.log(`${key}:`);
if (Array.isArray(value?._errors)) {
value._errors.forEach((errorMessage: string) => {
console.log(` - ${errorMessage}`);
});
}
}
});
};

// Remove .optional() from requried schema properties

const configSchema = z.object({
@@ -33,6 +47,14 @@ const configSchema = z.object({

export type Config = z.infer<typeof configSchema>;

const config = configSchema.parse(process.env);
const config = configSchema.safeParse(process.env);

if (!config.success) {
console.log('------------------------------------------------');
console.log('There is an error with the environment variables');
console.log('------------------------------------------------');
console.log(prettyPrintErrors(config.error));
process.exit(1);
}

export default config;
export default config.data;