Skip to content

Commit

Permalink
Merge pull request #9 from agrostar/vsc#10_env-vars
Browse files Browse the repository at this point in the history
replace $env.X instances in values of variables with process.env[X]
  • Loading branch information
vasansr authored Jun 29, 2024
2 parents 3498b60 + 00b55c0 commit 98f1c1c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
7 changes: 4 additions & 3 deletions src/replaceVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,10 @@ export function replaceVariablesInRequest(request: RequestSpec, variables: Varia

type keyOfHttp = Exclude<keyof typeof request.httpRequest, "method">;
const httpPropertiesToReplace: string[] = ["baseUrl", "url", "params", "headers", "body"];
httpPropertiesToReplace.forEach((key) => {
const replacedData = replaceVariables(request.httpRequest[key as keyOfHttp], variables);
request.httpRequest[key as keyOfHttp] = replacedData.data;
httpPropertiesToReplace.forEach((prop) => {
const httpKey = prop as keyOfHttp;
const replacedData = replaceVariables(request.httpRequest[httpKey], variables);
request.httpRequest[httpKey] = replacedData.data;
undefs.push(...replacedData.undefinedVars);
});

Expand Down
29 changes: 23 additions & 6 deletions src/variableParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ export function getEnvironments(bundleContent: string | undefined, varFileConten
return [...uniqueNames];
}

function replaceEnvironmentVariables(vars: Variables): Variables {
const PREFIX = "$env.";

const getVal = (val: any): any => {
if (typeof val !== "string" || !val.startsWith(PREFIX)) return val;

const envVarName = val.slice(PREFIX.length);
return envVarName in process.env ? process.env[envVarName] : val;
};

const replacedVars: Variables = {};
for (const key in vars) replacedVars[key] = getVal(vars[key]);

return replacedVars;
}

export function loadVariables(
envName: string | undefined,
bundleContent: string | undefined,
Expand All @@ -46,15 +62,16 @@ export function loadVariables(
if (!envName) return {};

const allBundleVariables = getBundleVariables(bundleContent);
const bundleVars = allBundleVariables.hasOwnProperty(envName) ? allBundleVariables[envName] : {};
const bundleVars: Variables = allBundleVariables[envName] ?? {};

let envVars = {};
const envVars: Variables = {};
varFileContents.forEach((fileContents) => {
const parsedData = YAML.parse(fileContents);
if (parsedData && isDict(parsedData[envName])) {
Object.assign(envVars, parsedData[envName]);
}
if (parsedData && isDict(parsedData[envName])) Object.assign(envVars, parsedData[envName]);
});

return Object.assign({}, envVars, bundleVars);
const basicVars = Object.assign({}, envVars, bundleVars);
const vars = replaceEnvironmentVariables(basicVars);

return vars;
}

0 comments on commit 98f1c1c

Please sign in to comment.