diff --git a/src/index.ts b/src/index.ts index c55cdcc..22b5edc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,8 @@ -import { Elysia } from "elysia"; -import { routes } from "./routes"; +import { validateEnv } from "./utils/startups/validateEnv"; +validateEnv(); + +const { Elysia } = await import("elysia"); +const { routes } = await import("./routes"); const app = new Elysia().use(routes).listen(process.env.PORT || 3000); diff --git a/src/utils/startups/validateEnv.ts b/src/utils/startups/validateEnv.ts new file mode 100644 index 0000000..61ac380 --- /dev/null +++ b/src/utils/startups/validateEnv.ts @@ -0,0 +1,37 @@ +import fs from "fs"; + +export const validateEnv = () => { + if (!fs.existsSync(".env")) { + if (fs.existsSync(".env.example")) { + console.error("โš ๏ธ .env file not found"); + console.warn("๐Ÿ“ Creating .env file from .env.example, please wait..."); + fs.copyFileSync(".env.example", ".env"); + console.warn( + "๐Ÿ–Š๏ธ .env file successfully created please fill in the value in each key needed" + ); + process.exit(1); + } else { + console.error( + `โŒ Can't validate environment variable because can't find .env.example file. seems to be missing files please re-pull with โ€œgit pull mainโ€` + ); + process.exit(1); + } + } + + const exampleKeys = fs + .readFileSync(".env.example", "utf-8") + .split("\n") + .map((line) => line.split("=")[0].trim()) + .filter((key) => key && !key.startsWith("#")); + + const missingKeys = exampleKeys.filter( + (key) => !process.env[key] || process.env[key].trim() === "" + ); + + if (missingKeys.length > 0) { + console.error("โŒ ENV error - missing key:"); + missingKeys.forEach((k) => console.error(` - ${k}`)); + console.error(`check your .env file and make sure all keys are filled in`); + process.exit(1); + } +};