Major update: Add Environment variables support

This commit is contained in:
Benjamin Toby
2024-10-16 09:40:21 +01:00
parent ed5248a43f
commit f56a63b2f2
8 changed files with 110 additions and 22 deletions
+2 -2
View File
@@ -5,11 +5,11 @@
* @param {number} [time]
* @returns
*/
async function delay(time) {
async function delay(time = 500) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, time || 500);
}, time);
});
}
+52
View File
@@ -0,0 +1,52 @@
// @ts-check
const fs = require("fs");
const path = require("path");
/**
*
* @param {HandleEnvVarsFnParams} param0
* @returns {string}
*/
function handleEnvVars({ json }) {
let newJson = json;
try {
let envVars = { ...process.env };
const localEnvFilePath = path.resolve(process.cwd(), "./.env");
if (fs.existsSync(localEnvFilePath)) {
const localEnvText = fs.readFileSync(localEnvFilePath, "utf8");
const localEnvKeyPairArray = localEnvText
.split("\n")
.filter(
(keyPair) =>
keyPair &&
keyPair.match(/.{3,}/) &&
!keyPair.match(/^\#/)
)
.map((keyPair) => keyPair.trim());
localEnvKeyPairArray.forEach((keyPair) => {
let keyPairArray = keyPair.split("=");
const key = keyPairArray.shift();
const value = keyPairArray.join("=");
const newEnvObject = {};
newEnvObject[key] = value;
envVars = { ...envVars, ...newEnvObject };
});
}
for (let key in envVars) {
newJson = newJson.replaceAll(`$${key}`, String(envVars[key]));
}
} catch (error) {
console.log(`Error replacing Environment variables`, error.message);
return json;
}
return newJson;
}
module.exports = handleEnvVars;