feat: move testing code to js-sandbox

This commit is contained in:
Andrew Bastin
2021-09-25 01:09:48 +05:30
parent 166f9e817b
commit 9454d8c100
4 changed files with 98 additions and 499 deletions

View File

@@ -1,42 +1,31 @@
import { runPreRequestScript } from "@hoppscotch/js-sandbox"
import {
getCurrentEnvironment,
getGlobalVariables,
} from "~/newstore/environments"
import { getRESTRequest } from "~/newstore/RESTSession"
export default function getEnvironmentVariablesFromScript(script: string) {
const _variables: Record<string, string> = {}
export const getCombinedEnvVariables = () => {
const variables: { key: string; value: string }[] = [...getGlobalVariables()]
const currentEnv = getCurrentEnvironment()
for (const variable of getCurrentEnvironment().variables) {
const index = variables.findIndex((v) => variable.key === v.key)
for (const variable of currentEnv.variables) {
_variables[variable.key] = variable.value
}
const globalEnv = getGlobalVariables()
if (globalEnv) {
for (const variable of globalEnv) {
_variables[variable.key] = variable.value
if (index === -1) {
variables.push({
key: variable.key,
value: variable.value,
})
} else {
variables[index].value = variable.value
}
}
try {
// the pw object is the proxy by which pre-request scripts can pass variables to the request.
// for security and control purposes, this is the only way a pre-request script should modify variables.
const pw = {
environment: {
set: (key: string, value: string) => (_variables[key] = value),
},
env: {
set: (key: string, value: string) => (_variables[key] = value),
},
// globals that the script is allowed to have access to.
}
// run pre-request script within this function so that it has access to the pw object.
// eslint-disable-next-line no-new-func
new Function("pw", script)(pw)
} catch (_e) {}
return _variables
return variables
}
export const getFinalEnvsFromPreRequest = () =>
runPreRequestScript(
getRESTRequest().preRequestScript,
getCombinedEnvVariables()
)