docs: 完善项目说明和注释
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import "dotenv/config";
|
||||
import { z } from "zod";
|
||||
|
||||
// 所有运行时配置都从环境变量读取,并在启动时一次性校验。
|
||||
// 这样数据库密码、端口等配置错误会在服务启动阶段暴露,而不是等到请求进来才失败。
|
||||
const envSchema = z.object({
|
||||
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
|
||||
PORT: z.coerce.number().int().positive().default(3000),
|
||||
|
||||
DB_HOST: z.string().min(1),
|
||||
DB_PORT: z.coerce.number().int().positive().default(3306),
|
||||
DB_USER: z.string().min(1),
|
||||
DB_PASSWORD: z.string().min(1),
|
||||
DB_NAME: z.string().min(1),
|
||||
DB_CONNECTION_LIMIT: z.coerce.number().int().positive().default(10)
|
||||
});
|
||||
|
||||
const result = envSchema.safeParse(process.env);
|
||||
|
||||
if (!result.success) {
|
||||
// 这里直接退出进程,因为配置错误属于“服务无法安全启动”的问题。
|
||||
console.error("环境变量配置错误,请对照 .env.example 检查:");
|
||||
console.error(z.treeifyError(result.error));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 其他模块只从 env 读取已校验过的值,不再直接访问 process.env。
|
||||
export const env = result.data;
|
||||
Reference in New Issue
Block a user