Continuing the discussion from Sharing tips and tricks with others in the Postman community:
In @danny-dainton’s topic above, he shared a way to keep variables with a given prefix, it was funny when I was reading it last night because I had to solve the exact same problem the day before. My solution is just a little different from Danny’s and thought I would share it too
In essence, if and when I want to clean up my environment variables, I set env var OkToClear
to 'true'
, and then use an array varsToKeep
that lists the variables I want to keep.
OkToClear = 'true'
varsToKeep = ["OkToClear","HostURL","debug","assetsIfModifiedSince","varsToKeep"]
... other vars ...
code snippet
if( pm.environment.has("OkToClear")
&& pm.environment.get("OkToClear")==="true"
&& pm.environment.has("varsToKeep")
) {
const varsToKeepJSON = pm.environment.get("varsToKeep");
let varsToKeep, tmp = {};
// ignore JSON parsing errors
try{varsToKeep = varsToKeepJSON && JSON.parse(varsToKeepJSON);}catch(e){}
// save the variables to keep to tmp
varsToKeep && varsToKeep.forEach(
variable => tmp[variable] = pm.environment.has(variable) && pm.environment.get(variable)
);
// clear the whole environment
pm.environment.clear();
// save all the variables we kept back to the environment
varsToKeep && varsToKeep.forEach(
variable => tmp[variable] && pm.environment.set(variable, tmp[variable])
);
// log the clean environment to console
console.log("Environment cleared to");
console.log(pm.environment.toObject());
}else{
console.log("Did not clear Environment variables. Check that Environment variable OkToClear = true");
}
Notes:
- I’m using short circuiting a bit here, which where commands prefixed by a logical expression are only executed when the logical expression evaluates to truthy. For example,
varsToKeep
is only assigned a value ifvarsToKeepJSON
has a value. - The
try{...}catch(e){}
is used to ignore exceptions during the JSON parsing. This is safe to do here because we always check thatvarsToKeep
is truthy before using it. - The arrow functions are a bit cryptic, but once you understand them they are way cool
. I will try and write a separate article on them, but in essence, for this example, they are simply 1 line functions used on each element of an array.
- The reason for the
OkToClear
flag is to make sure that when I share the collection with my colleagues that my code snippet doesn’t inadvertently delete all their environment variables which they may have carefully setup for their test
links:
- short circuiting
Expressions and operators - JavaScript | MDN - truthy
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN - arrow functions
Arrow function expressions - JavaScript | MDN