Last active
July 1, 2022 19:51
-
-
Save rproman/28a7c7bf4d203d390d26ee708d99a71e to your computer and use it in GitHub Desktop.
Programmatically persist the current values to initial values of environment variables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated implementation using an array of environment keys code optimization.