Using external libraries in postman and there by using custom handlebar helpers in Postman visualization!

Postman allows you to use CDN libraries in the script session,

so here we are using the CDN equivalent of the handlebar and then passing the compiled template to the postman visualizer

We can initialize CDN in two ways :

First Approach:

By initializing the CDN in global space using “new Function(cdn)()”

You can see the code below , but this will mess up global scope and can be used only once in the entire run



// you can call any package with min build in postman
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.js", (err, res) => {

    pm.environment.set("res", res.text());
    // intialize the min.js
    new Function(pm.environment.get("res"))();

    //create template soource
    var source =
        `{{#ifCond v1 v2}}
    {{v1}} is equal to {{v2}}
{{else}}
    {{v1}} is not equal to {{v2}}
{{/ifCond}}`;

    //you can call methods in the cdn file using this keyword
    //here we are registring handlebar

    Handlebars.registerHelper('ifCond', function (v1, v2, options) {
        if (v1 === v2) {
            return options.fn(this);
        }
        return options.inverse(this);
    });


    //compile the template
    var template = Handlebars.compile(source);


    //data to be passed 
    // try v1 and v2 with same and different values and observe the output in visualization tab
    var data = {
        "v1": "test",
        "v2": "test",
    };

    // passing the data to template
    var result = template(data);

    //visualizing it 
    pm.visualizer.set(result)
})

Second Approach:

you can call any package with min build in postman

this initializes the functions in local scope so it won’t mess up the global space and cause issues

pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js", (err, res) => {

    pm.environment.set("res", res.text());

    // intialize the min.js

    eval(pm.environment.get("res"));

    //create template soource

    var source =

        `{{#ifCond v1 v2}}

    {{v1}} is equal to {{v2}}

{{else}}

    {{v1}} is not equal to {{v2}}

{{/ifCond}}`;

    //you can call methods in the cdn file using this keyword

    //here we are registring handlebar

    this.Handlebars.registerHelper('ifCond', function (v1, v2, options) {

        if (v1 === v2) {

            return options.fn(this);

        }

        return options.inverse(this);

    });

    //compile the template

    var template = this.Handlebars.compile(source);

    //data to be passed 

    // try v1 and v2 with same and different values and observe the output in visualization tab

    var data = {

        "v1": "test",

        "v2": "test",

    };

    // passing the data to template

    var result = template(data);

    //visualizing it 

    pm.visualizer.set(result)

})
4 Likes