I have a call that grabs a token from one of my servers. A token has a lifespan of 15 minutes. I have code in the Pre-Request that checks to see if 15 minutes has passed. If it has, it will grab a new token. If not, I use the pm.execution.setNetxRequest(null); but no matter what, it still executes the call.
Is it possible to halt a request from being made within its own Pre-request?
Hey @G-Laser
What’s the full script you have, it will make it a lot easier to provide additional help here.
Are you using this as a standalone request or running it with the Collection Runner?
Right now, it’s just a stand-alone request. My other tests that use it inherit the token from what that call returns.
Here is that calls Pre-request.
require("btoa");
const tokenTimestamp = pm.environment.get('token_timestamp');
const timeDifference = Date.now() - tokenTimestamp;
const minutes = Math.floor(timeDifference / (1000 * 60));
console.log("Number of minutes: " + minutes);
if(tokenTimestamp == null || minutes > 15) {
pm.environment.set("base64_encoded_client", btoa(pm.environment.get("username") + ":" + pm.environment.get("password")));
} else {
pm.execution.setNextRequest(null);
console.log("Call cancelled");
}
In the Post-response, it just sets the tokens and the current timestamp since I expect it to only run if pm.execution.setNextRequest(null) is not executed.
The setNextRequest
function can only be used with the Collection Runner, it won’t do anything if it’s used in a standalone request.
pm.setNextRequest() sets the next request that will run after the current request has completed. (Including any pre or post request code).
It will always run the current request.
Sounds like you want the pm.execution.skipRequest() function.
https://blog.postman.com/optimize-your-api-testing-workflow-with-postmans-skip-request-feature
I have a few API’s where I have similar code. I normally put the code in the pre-request script at the folder or collection level, so it checks the token expiry for each request in that collection or folder. I don’t need to skip or change the execution flow that way. It will either get a new token or it won’t and won’t be reliant on the Collection Runner to work or test.