Skip to content

Commit

Permalink
feat(Utils): add env parser
Browse files Browse the repository at this point in the history
  • Loading branch information
ijsKoud committed Jun 20, 2023
1 parent 59b4ce4 commit f647acd
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"license": "MIT",
"type": "module",
"exports": {
"./regex.js": "./dist/src/regex.js",
"./env.js": "./dist/src/env.js",
"./types.js": "./dist/src/types.js",
"./constants.js": "./dist/src/constants.js",
"./RequestWithPagination.js": "./dist/src/RequestWithPagination.js"
Expand All @@ -16,8 +18,7 @@
"test": "vitest run"
},
"dependencies": {
"lru-cache": "^10.0.0",
"probot": "12.3.1"
"@snowcrystals/icicle": "^2.0.4"
},
"devDependencies": {
"@types/node": "^18.16.18",
Expand Down
51 changes: 51 additions & 0 deletions packages/utils/src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { config } from "dotenv";
config();

import { ZodError, z } from "zod";
import { Logger } from "@snowcrystals/icicle";
import { bold } from "colorette";
import { PRIVATE_KEY_REGEX } from "./regex.js";

const logger = new Logger();
const envSchema = z.object({
APP_ID: z.string(),
PRIVATE_KEY: z.string().regex(PRIVATE_KEY_REGEX),

WEBHOOK_SECRET: z.string(),

GITHUB_CLIENT_ID: z.string(),
GITHUB_CLIENT_SECRET: z.string(),

PORT: z.string().max(4),
NODE_ENV: z.string(),

REDIS_DATABASE_URL: z.string().url()
});

try {
envSchema.parse(process.env);
} catch (err) {
if (!(err instanceof ZodError)) {
console.error(err);
process.exit(1);
}

// Filter out missing ones
const missing = err.issues.filter((issue) => issue.message === "Required").map((issue) => bold(issue.path[0]));
logger.fatal(`The following environment variables are missing: ${missing}`);

const failedTest = err.issues.filter((issue) => issue.message !== "Required");
for (const failedItem of failedTest) {
// Environment variable
const path = failedItem.path[0];
logger.fatal(`[${path}]: Failed the test with reason: ${failedItem.message}`);
}

process.exit(1);
}

declare global {
namespace NodeJS {
interface ProcessEnv extends z.infer<typeof envSchema> {}
}
}
1 change: 1 addition & 0 deletions packages/utils/src/regex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const PRIVATE_KEY_REGEX = /\s*(\bBEGIN\b).*(PRIVATE KEY\b)\s*/gm;

0 comments on commit f647acd

Please sign in to comment.