Skip to content

Instantly share code, notes, and snippets.

@farithadnan
Created October 7, 2024 04:33
Show Gist options
  • Save farithadnan/9baf8406e89b5a11a4e17d887b0d612b to your computer and use it in GitHub Desktop.
Save farithadnan/9baf8406e89b5a11a4e17d887b0d612b to your computer and use it in GitHub Desktop.
Postman Script (Pre-request)
pm.test("Check for collection's variables..", function () {
let vars = ['client_id', 'client_secret', 'grant_type'];
vars.forEach(function (item, index, array) {
console.log(item, index);
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty;
});
if ((!pm.collectionVariables.get("access_token") && pm.collectionVariables.get("IS_TESTING"))
|| Date.now() > new Date(pm.collectionVariables.get("expires_in") * 1000)) {
var baseUrl = pm.collectionVariables.get("IS_TESTING") == "true" ? pm.collectionVariables.get("TESTING_URI") : pm.collectionVariables.get("PRODUCTION_URI");
var uploadBaseUrl = pm.collectionVariables.get("IS_TESTING") == "true" ? pm.collectionVariables.get("UPLOAD_TESTING_URI") : pm.collectionVariables.get("UPLOAD_PRODUCTION_URI");
pm.sendRequest({
url: baseUrl + 'oauth/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: pm.collectionVariables.get("client_id"), disabled: false },
{ key: "client_secret", value: pm.collectionVariables.get("client_secret"), disabled: false },
{ key: "grant_type", value: pm.collectionVariables.get("grant_type"), disabled: false },
]
}
}, function (err, res) {
if (err) {
console.log(err);
} else {
pm.test("Status code is 200", () => {
pm.expect(res).to.have.status(200);
});
let resJson = res.json();
pm.collectionVariables.set("BASE_URL", baseUrl);
pm.collectionVariables.set("UPLOAD_BASE_URL", uploadBaseUrl);
pm.collectionVariables.set("expires_in", resJson.expires_in);
pm.collectionVariables.set("access_token", resJson.access_token);
pm.collectionVariables.set("scope", resJson.scope);
pm.collectionVariables.set("token_type", resJson.token_type);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment