mirror of
https://github.com/karl0ss/homepage.git
synced 2025-05-04 14:33:41 +01:00
Cache config env variables & check if config contains variables before substitution
This commit is contained in:
parent
e0f1aae4d5
commit
b2d22d7574
@ -2,8 +2,13 @@
|
|||||||
import { join } from "path";
|
import { join } from "path";
|
||||||
import { existsSync, copyFile, readFileSync } from "fs";
|
import { existsSync, copyFile, readFileSync } from "fs";
|
||||||
|
|
||||||
|
import cache from "memory-cache";
|
||||||
import yaml from "js-yaml";
|
import yaml from "js-yaml";
|
||||||
|
|
||||||
|
const cacheKey = "homepageEnvironmentVariables";
|
||||||
|
const homepageVarPrefix = "HOMEPAGE_VAR_";
|
||||||
|
const homepageFilePrefix = "HOMEPAGE_FILE_";
|
||||||
|
|
||||||
export default function checkAndCopyConfig(config) {
|
export default function checkAndCopyConfig(config) {
|
||||||
const configYaml = join(process.cwd(), "config", config);
|
const configYaml = join(process.cwd(), "config", config);
|
||||||
if (!existsSync(configYaml)) {
|
if (!existsSync(configYaml)) {
|
||||||
@ -27,20 +32,30 @@ export default function checkAndCopyConfig(config) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function substituteEnvironmentVars(str) {
|
function getCachedEnvironmentVars() {
|
||||||
const homepageVarPrefix = "HOMEPAGE_VAR_";
|
let cachedVars = cache.get(cacheKey);
|
||||||
const homepageFilePrefix = "HOMEPAGE_FILE_";
|
if (!cachedVars) {
|
||||||
|
// initialize cache
|
||||||
|
cachedVars = Object.entries(process.env).filter(([key, ]) => key.includes(homepageVarPrefix) || key.includes(homepageFilePrefix));
|
||||||
|
cache.put(cacheKey, cachedVars);
|
||||||
|
}
|
||||||
|
return cachedVars;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function substituteEnvironmentVars(str) {
|
||||||
let result = str;
|
let result = str;
|
||||||
Object.keys(process.env).forEach(key => {
|
if (result.includes('{{')) { // crude check if we have vars to replace
|
||||||
|
const cachedVars = getCachedEnvironmentVars();
|
||||||
|
cachedVars.forEach(([key, value]) => {
|
||||||
if (key.startsWith(homepageVarPrefix)) {
|
if (key.startsWith(homepageVarPrefix)) {
|
||||||
result = result.replaceAll(`{{${key}}}`, process.env[key]);
|
result = result.replaceAll(`{{${key}}}`, value);
|
||||||
} else if (key.startsWith(homepageFilePrefix)) {
|
} else if (key.startsWith(homepageFilePrefix)) {
|
||||||
const filename = process.env[key];
|
const filename = value;
|
||||||
const fileContents = readFileSync(filename, "utf8");
|
const fileContents = readFileSync(filename, "utf8");
|
||||||
result = result.replaceAll(`{{${key}}}`, fileContents);
|
result = result.replaceAll(`{{${key}}}`, fileContents);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user