Created
August 25, 2023 15:04
-
-
Save ozcanzaferayan/6465bead7a386d6123eb1e0152cb6c61 to your computer and use it in GitHub Desktop.
Postman pre-request script for setting token
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
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