preRequest.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {
  2. getCurrentEnvironment,
  3. getGlobalVariables,
  4. } from "~/newstore/environments"
  5. export default function getEnvironmentVariablesFromScript(script: string) {
  6. const _variables: Record<string, string> = {}
  7. const currentEnv = getCurrentEnvironment()
  8. for (const variable of currentEnv.variables) {
  9. _variables[variable.key] = variable.value
  10. }
  11. const globalEnv = getGlobalVariables()
  12. if (globalEnv) {
  13. for (const variable of globalEnv) {
  14. _variables[variable.key] = variable.value
  15. }
  16. }
  17. try {
  18. // the pw object is the proxy by which pre-request scripts can pass variables to the request.
  19. // for security and control purposes, this is the only way a pre-request script should modify variables.
  20. const pw = {
  21. environment: {
  22. set: (key: string, value: string) => (_variables[key] = value),
  23. },
  24. env: {
  25. set: (key: string, value: string) => (_variables[key] = value),
  26. },
  27. // globals that the script is allowed to have access to.
  28. }
  29. // run pre-request script within this function so that it has access to the pw object.
  30. // eslint-disable-next-line no-new-func
  31. new Function("pw", script)(pw)
  32. } catch (_e) {}
  33. return _variables
  34. }