Collection-level object function called from pre-request script

I have this pre-request script at the collection level:

Util = {}
Util.foo = () => { 
  pm.request.url = "foo"
  console.log("func", pm.request)
}

And then this in pre-request script:

Util.foo()
console.log("request", pm.request)

When I run this request, it logs the changed url once, but then ends up running the original request.

If instead I call Util.foo() in the collection script or if I just put pm.request.url="foo" in the request pre- script, then it works as intended (fails, because it can’t find foo).

I wonder if there is some work around for this. I want to be able to define a function at the collection level, that will alter the url for some requests (folders actually), but it is rather tedious to have to write in in-line everywhere :frowning:

You have to send the pm method with the request.

utils = {
    foo: function (pm) {
        pm.request.url = "https://postman-echo.com/post"
        console.log("func", pm.request)
        return 'hello';
    }
};

You then call it using…

utils.foo(pm);

image

This looks like a candidate to add to a script in the new Package Library - This types of workarounds are only there due to not having the capability to create those global, team based functions.

const foo = () => {
    pm.request.url = "https://postman-echo.com/post"
    console.log("func", pm.request);
}

module.exports = { foo }

I kept the method as a GET on the main request so that you could see the request return a 404 due to the url change in the script. You’d also not need to add pm as an argument to the function.

This Package Library was only add in V11 so there will be certain scenarios that might need a bit of work but this simple case will work.

Yeah, packages look nice, but I don’t think I can use them:

  • we used newman 6.0, that doesn’t even have p.executions yet … no idea how long it will be before it supports packages
  • it looks like packages requires access to internet at runtime, which is less than ideal … some of our environments are “air-sealed”
  • frankly, having to type require in every script seems a bit … tedious. I wish there was a way to just import the package at the collection level …

That was added in version 6.1 of Newman so you’d need to update your version to access the pm.executions.* as well as a few other updates.

The packages are not exported with the Collections so Newman wouldn’t have any connection to those as Newman is an independent npm package.

You also access packages at the Collection and Folder level.

The Postman CLI can access and run the scripts but these can only be utilised if you’re on a certain plan.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.