Skip to content

Instantly share code, notes, and snippets.

@rproman
Last active July 1, 2022 19:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rproman/28a7c7bf4d203d390d26ee708d99a71e to your computer and use it in GitHub Desktop.
Save rproman/28a7c7bf4d203d390d26ee708d99a71e to your computer and use it in GitHub Desktop.
Programmatically persist the current values to initial values of environment variables.
let headers = {'X-Api-Key' : ''};
headers[`X-Api-Key`] = String(pm.variables.get("postman_api_key"));
// Note: Update the environment UID if no longer sync
const postman_api_url = "https://api.getpostman.com/environments/" + pm.environment.get("uid");
let requestOptions = {
url: postman_api_url,
method: 'GET',
header: headers
}
// retrieve first the complete set of current environment data
pm.sendRequest(requestOptions, (error, response) => {
if (error) {
console.error("Error retrieving current environment data: " + error)
} else {
let body = response.json()
console.log("Current Environment: " + JSON.stringify(body))
// Update this env_keys array with the environment variable keys to update or create
const env_keys = [
'firstname',
'lastname',
'totalprice',
'depositpaid',
'checkin',
'checkout',
'additionalneeds',
'bookingid'];
// start updating target environment variables
env_keys.forEach((env_val) => {
let index = body.environment.values.findIndex((item) => {
return (item.key === env_val)
})
if (index != -1) {
body.environment.values[index].value = String(pm.environment.get(env_val));
} else {
let vars = {key: '', value: ''};
vars.key = String(env_val);
vars.value = String(pm.environment.get(env_val));
console.log("vars: " + JSON.stringify(vars));
body.environment.values.push(vars);
}
})
console.log("New Environment Variables: " + JSON.stringify(body))
requestOptions = {
url: postman_api_url,
method: 'PUT',
header: headers,
body: {
mode: 'raw',
raw: body
}
}
//console.log("JSON.stringify(): " + JSON.stringify(requestOptions));
pm.sendRequest(requestOptions, (error, response) => {
if (error) {
console.error("Error updating current environment: " + error)
}
})
}
@rproman
Copy link
Author

rproman commented Jul 1, 2022

Updated implementation using an array of environment keys code optimization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment