diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 39baaf8e..8f728f19 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -43,7 +43,8 @@ import { checkMemorySessionId, clearSessionMemoryFromViewMessageDialog, getUserHome, - replaceChatHistory + replaceChatHistory, + replaceEnvVariables } from './utils' import { cloneDeep, omit, uniqWith, isEqual } from 'lodash' import { getDataSource } from './DataSource' @@ -1381,6 +1382,10 @@ export class App { const chatflowid = req.params.id let incomingInput: IncomingInput = req.body + if (incomingInput.question) { + incomingInput.question = await replaceEnvVariables(incomingInput.question, this.AppDataSource) + } + let nodeToExecuteData: INodeData const chatflow = await this.AppDataSource.getRepository(ChatFlow).findOneBy({ diff --git a/packages/server/src/utils/index.ts b/packages/server/src/utils/index.ts index adec01cd..d3575388 100644 --- a/packages/server/src/utils/index.ts +++ b/packages/server/src/utils/index.ts @@ -954,3 +954,29 @@ export const getAllValuesFromJson = (obj: any): any[] => { extractValues(obj) return values } + +export const replaceEnvVariables = async (question: string, appDataSource: DataSource): Promise => { + // the incoming question can have more than one env variable with the pattern {{ env.VARIABLE_NAME }} + // extract all the env variables from the question and iterate through them + const envVariables = question.match(/{{[^}]*}}/g) + if (envVariables) { + for (const envVariable of envVariables) { + // this is needed as the user can have spaces between the curly braces and the env keyword + // extract the variable name from the env variable + const variableName = envVariable.replace(/{{\s*env.|\s*}}/g, '') + // get the value of the env variable from the database + const variable = await appDataSource.getRepository(Variable).findOneBy({ + name: variableName + }) + if (variable) { + let value = variable.value + if (variable.type === 'runtime') { + value = process.env[variable.name] as string + } + // replace the env variable with the value from the database + question = question.replace(envVariable, value) + } + } + } + return question +}