Skip to content

Instantly share code, notes, and snippets.

@ozcanzaferayan
Created August 25, 2023 15:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozcanzaferayan/6465bead7a386d6123eb1e0152cb6c61 to your computer and use it in GitHub Desktop.
Save ozcanzaferayan/6465bead7a386d6123eb1e0152cb6c61 to your computer and use it in GitHub Desktop.
Postman pre-request script for setting token
const authRequest = {
url: `${pm.collectionVariables.get("baseUrl")}/auth`,
method: "POST",
header: {
"Version": pm.collectionVariables.get("Version"),
},
body: {
mode: "application/json",
raw: JSON.stringify({
username: pm.collectionVariables.get("Username"),
password: pm.collectionVariables.get("Password"),
}),
},
};
if (
!pm.collectionVariables.get("Token") ||
!pm.collectionVariables.get("TokenExpiry")
) {
console.log("Token or expiry date are missing, getting token");
} else if (pm.collectionVariables.get("TokenExpiry") <= new Date().getTime()) {
console.log("Token is expired, getting token...");
} else {
// Use same token
return;
}
pm.sendRequest(authRequest, function (err, res) {
if (err) {
console.log(err);
return;
}
var responseJson = res.json();
console.log("responseJSON", responseJson)
pm.collectionVariables.set("Token", responseJson.result.token);
var expiryDate = new Date();
expiryDate.setHours(expiryDate.getHours() + 4);
pm.collectionVariables.set("TokenExpiry", expiryDate.getTime());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment