Use part of 'var template globally?

We are writing a lot of visualizations - about 422. Right now our workflow is that that in the viz there is the component that handles grabbing data - either lodash or handlebars - then there is the visualization libraries - highcharts, datatables, etc. If we look at our 422 visualizations - it boils down to about 10 unique configurations of highcharts and datatables. To make them unique we use container names based on postman unique data - such as the request id.

Instead of having to constantly copy paste the same code over and over - it would be great to setup these component as somethign that can be called in each test after the var template.

We tried putting the script components in an environment variable and calling it using pm.get environment - but that didn’t work. Perhaps order of operation?

Would be great if someone knows a way to make this simpler. The risk of constantly copy pasting is a risk filled endeavor for the brave of heart.

Is there a way to centrally store these scripts and call them in the test script?

Hey Thomas,

For starters, I’d love to know the types of visualizations you are creating with highcharts and datatables and a bit about the underlying API that means you’re implementing this across the spectrum. This is great to hear and may provoke a few additional thoughts with that context.

A few things to consider:

  1. The environment approach is a good one. When you run pm.environment.get('varName'), it will return a String, so actually you’ll need to eval that, e.g. eval(pm.environment.get('varName')). This will execute your code right away. If the code you’re placing in the environment is not self executing, you might like to make it so, else remember to execute the underlying function eval(pm.environment.get('varName')().

  2. Consider making use of collection test scripts/variables. Right click on any collection, hit “Edit”, note you can apply a test script to run for every request inside the collection. You can also store variables (code snippets) at the collection level.

  3. You could retrieve code snippets via an API too via pm.sendRequest (https://learning.getpostman.com/docs/postman/scripts/postman-sandbox-api-reference/#pmsendrequest) in the Sandbox. This would still involve eval and would require you to hold your snippets outside of Postman, and does mean you would want to consider the security implications of pulling code over a network call and executing it. Thus, this isn’t my first recommendation but can sometimes be handy for local/isolated networks.

If you run into any issues, take a look inside the console for errors and report back. Also keen to hear more about your use case as detailed above.

Cheers,
Matt

Matt,

I can show you samples of our visualizations - in fact - happy to provide them to the library - sharing is caring after all. We are a fintech startup - so our viz’s deal with things like vwap - volume weighted average pricing - all the way to transaction ledgers and trial balance reporting. Very dull stuff -but exciting to us.

I have tried the collection variables path - i.e. I took out my entire code - below the var template - which includes HTML style tags to script src pulls to functions. And then pmget variable. What I did not do is use the eval setting - I’m definitely going to try that!

Let me know the best way to share what we are doing - we are super excited about the postman viz capability because it lets us prototype UX. We are even doing editable data tables where we then post back through our apis. In once case we even built a viz (as our clients LOVE excel) that is essentially an api call to Excel - processes the binaries, uses lodash to reformat the resulting javascript object into nested arrays - then processes that data via an ajax post back into our system. So the user gets - 1. interaction, 2. view of the json information, and 3 - automated workflow to post it to our system. The rest is just viz stuff - representing data in tables, charts, line charts, polar charts - etc.

Tom

so - I tried the eval - but it didn’t produce the visualization as intended. There were also no script errors. But it wasnt’ taking any of my classes into effect. I then tried only taking items between tags and inserting that with the eval statement - to no effect. I then tried the ${ notation as its within the var template - still - nothing. Perhaps I need a noob tutorial.

Hi Tom,

That’s really interesting stuff! Visualizer is still a relatively recent release so we’re always excited to learn more about how folks are using it.

It sounds like there might be an issue with the scope of a few variables once they get abstracted and run with eval. Seeing the collection you have will probably be a lot more effective than going back and forth trying to explain what your code is doing on here, unless you can provide code snippets.

With regards to sharing that collection - you could add as a template as you mention. I can dig in from there.

If there’s anything you’d rather not share on here - feel free to drop me a message on here with a collection export:
https://learning.getpostman.com/docs/postman/collections/data-formats/#collections

Cheers,
Matt

Here is an example - the following code is needed on all of our visualizations. We update it sometimes and need it to be the same everywhere. As this exists between the var template ’ - I have tried multiple ways of trying to pull it in from a central location - one place for everyone:

${eval(pm.environment.get(‘codePdf’))} - does not work. When I do that it returns an error in the script.

Our scripts have 3 - 8 components - the most common use case is 3.

  1. Lodash or handlebars to gather json data from the response. Handlebars within the template lodash outside using var
  2. Script libraries for either datatables or highcharts
  3. Script libraries for jsPDF (tried pdfmake but it has unsafe eval - which I can’t seem to find a way around - including setting meta tags in a header)

The below is our jsPdf script. Runs between after var template’ - used to allow users to pdf the reports we have developed. We would love to have this script in one location. I liked the variable idea - but it simple does not work. So we are copy pasting like little monkeys. Any thoughts on how to make the script below standard such tat we can call it from within the var template’ tags.

<!-- Creation of PDF generation from Postman visual -->
<script>
    function generate() {
    //Creation of PDF document
    let doc = new jsPDF('l', 'pt');
    const totalPagesExp = '{total_pages_count_string}';
    var elem = document.getElementById('${pm.info.requestId}');
    var data = doc.autoTableHtmlToJson(elem);
    doc.autoTable(data.columns, data.rows, {
        headStyles: {
            cellWidth: 'wrap',
            fontSize: 10,
            lineWidth: 0.5,
            lineColor: [0, 0, 0],
            textColor: [0, 0, 0],
            fillColor: [211,211,211]
        },
        bodyStyles: {
            cellWidth: 'wrap',
            fontSize: 8,
            lineWidth: 0.5,
            lineColor: [0, 0, 0],
            textColor: [0, 0, 0],
            fillColor: [255,255,255]
        },
        //Formatting of pages
        didDrawPage: function (data) {
            //Summa logo on top of the page
            doc.addImage('${pm.variables.get("summa")}', 'PNG', 20, 20, 145, 42.63);
            //Font sizes of report information
            doc.setFontSize(8);
            //Report information: portfolio name, knowledge time and report time
            doc.text(35, 75, '${pm.variables.get("portfolioName")}');
            doc.text(35, 85, '${pm.variables.get("reportTime")}');
            doc.text(35, 95, '${pm.variables.get("knowledgeTime")}');
            //Page numbers
            var str = "Page " + doc.internal.getNumberOfPages()
            if (typeof doc.putTotalPages === 'function') {
                str = str + " of " + totalPagesExp;
            };
            //Page size
            var pageSize = doc.internal.pageSize;
            var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
            doc.text(str, data.settings.margin.left, pageHeight - 10);
        },
        margin: {
            top: 100
        }
    });
    //Number of pages
    if (typeof doc.putTotalPages === 'function') {
        doc.putTotalPages(totalPagesExp);
    }
    //--------------------------------------------------------------------------------------------------START
    //Change name of report if desired
    doc.save('${pm.info.requestName}${pm.variables.get("reportTime")}.pdf');
    //--------------------------------------------------------------------------------------------------END
}