Skip to content

Commit 158cc1a

Browse files
committed
feat: make envConfig typesafe
1 parent c6e9347 commit 158cc1a

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

src/app.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,25 @@ import userRoute from "@/routes/users.routes";
77
import { middlewares } from "@/middlewares";
88

99
const app: Express = express();
10+
// connect to database
11+
/*
12+
* Example conncting to MongoDB using mongoose
13+
*
14+
async function connectToMongoDB() {
15+
try {
16+
await mongoose.connect(env.MONGODB_URI, {
17+
connectTimeoutMS: 1000000000,
18+
});
19+
console.log("✅ Connected to MongoDB");
20+
} catch (error) {
21+
console.error("❌ MongoDB connection error:", error);
22+
process.exit(1); // Exit if DB connection fails
23+
}
24+
}
1025
26+
connectToMongoDB().catch((err) => console.error(err));
27+
28+
*/
1129
// Middlewares
1230
app.use(cors());
1331
app.use(express.json());

src/configs/envConfig.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,22 @@ try {
1414
process.exit(1);
1515
}
1616

17-
// Define Zod schema for validation
17+
// Define Zod schema for validation and transformation
1818
const envSchema = z.object({
1919
PORT: z
2020
.string()
2121
.default("3000")
22-
.transform(Number)
23-
.refine((val) => !isNaN(val), {
24-
message: "PORT must be a valid number",
22+
.transform((val) => {
23+
const parsed = Number(val);
24+
if (Number.isNaN(parsed)) throw new Error("PORT must be a valid number");
25+
return parsed;
2526
}),
2627
HOST: z.string().default("localhost"),
2728
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
2829
DB_URI: z.string().url("DB_URI must be a valid URL"),
2930
});
3031

31-
// Validate process.env
32+
// Validate process.env and infer typed env object
3233
const parsedEnv = envSchema.safeParse(process.env);
3334

3435
if (!parsedEnv.success) {
@@ -37,6 +38,6 @@ if (!parsedEnv.success) {
3738
process.exit(1);
3839
}
3940

40-
// ✅ Export validated, typed, and transformed env values
41-
export const env = parsedEnv.data;
41+
export type Env = z.infer<typeof envSchema>;
4242

43+
export const env: Env = parsedEnv.data;

0 commit comments

Comments
 (0)