From b7c2d13992042c152fb5b68767ee649d1a734d16 Mon Sep 17 00:00:00 2001 From: Akash K <57758277+amk-dev@users.noreply.github.com> Date: Wed, 10 May 2023 19:14:16 +0530 Subject: [PATCH] fix: invalid environment index can break the app (#3041) --- .../src/newstore/environments.ts | 46 +++++++++++-------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/packages/hoppscotch-common/src/newstore/environments.ts b/packages/hoppscotch-common/src/newstore/environments.ts index e77c3805a..326788f8e 100644 --- a/packages/hoppscotch-common/src/newstore/environments.ts +++ b/packages/hoppscotch-common/src/newstore/environments.ts @@ -37,13 +37,22 @@ type EnvironmentStore = typeof defaultEnvironmentsState const dispatchers = defineDispatchers({ setSelectedEnvironmentIndex( - _: EnvironmentStore, + store: EnvironmentStore, { selectedEnvironmentIndex, }: { selectedEnvironmentIndex: SelectedEnvironmentIndex } ) { - return { - selectedEnvironmentIndex, + if ( + selectedEnvironmentIndex.type === "MY_ENV" && + !!store.environments[selectedEnvironmentIndex.index] + ) { + return { + selectedEnvironmentIndex, + } + } else { + return { + type: "NO_ENV_SELECTED", + } } }, appendEnvironments( @@ -325,21 +334,22 @@ export const selectedEnvironmentIndex$ = environmentsStore.subject$.pipe( distinctUntilChanged() ) -export const currentEnvironment$ = environmentsStore.subject$.pipe( - map(({ environments, selectedEnvironmentIndex }) => { - if (selectedEnvironmentIndex.type === "NO_ENV_SELECTED") { - const env: Environment = { - name: "No environment", - variables: [], +export const currentEnvironment$: Observable = + environmentsStore.subject$.pipe( + map(({ environments, selectedEnvironmentIndex }) => { + if (selectedEnvironmentIndex.type === "NO_ENV_SELECTED") { + const env: Environment = { + name: "No environment", + variables: [], + } + return env + } else if (selectedEnvironmentIndex.type === "MY_ENV") { + return environments[selectedEnvironmentIndex.index] + } else { + return selectedEnvironmentIndex.environment } - return env - } else if (selectedEnvironmentIndex.type === "MY_ENV") { - return environments[selectedEnvironmentIndex.index] - } else { - return selectedEnvironmentIndex.environment - } - }) -) + }) + ) export type AggregateEnvironment = { key: string @@ -358,7 +368,7 @@ export const aggregateEnvs$: Observable = combineLatest( map(([selectedEnv, globalVars]) => { const results: AggregateEnvironment[] = [] - selectedEnv.variables.forEach(({ key, value }) => + selectedEnv?.variables.forEach(({ key, value }) => results.push({ key, value, sourceEnv: selectedEnv.name }) ) globalVars.forEach(({ key, value }) =>