The Rest connector sometimes requires one to manipulate the data between calls, an example of this might be where a call will give you a batch size and total documents field.
For this example we are going to use the post-man echo functionality to retrieve a doc with the following fields:
We will use the JS script to cycle through the DocNum and Page number until you get to the end. Then start again from the beginning as seen in the above.
I am no JS expert so I am going to ask ChatGPT to build the code for me. see transcript here.
The output given needs a bit of cleaning up. they referenced the fields with fields instead of this... and gave us a bit more than we need. Utopia will wrap the script up correctly as a function so we only need to input the actual scripts. The return syntax can also be adjusted as below. So this is a good starting point:
let batch =parseInt(args.batch,10);let total =parseInt(args.total,10);let docNo =parseInt(args.docNum,10);let pageNo =parseInt(this.pageNo,10);// Perform the specified calculationlet newDocNo = docNo + batch;if (newDocNo > total) {// Reset docNo and pageNo if newDocNo is greater than total docNo =1; pageNo =1; } else {// Update docNo to newDocNo and increment pageNo docNo = newDocNo; pageNo +=1; }// Return the updated docNo and pageNo in the specified formatreturn {'docNo': docNo,'pageNo': pageNo};
we can now remove the spaces and comments and put it in a form we can use in the connector
let batch = parseInt(args.batch, 10); let total = parseInt(args.total, 10); let docNo = parseInt(args.docNum, 10); let pageNo = parseInt(this.pageNo, 10); let newDocNo = docNo + batch; if (newDocNo > total) { docNo = 1; pageNo = 1;} else { docNo = newDocNo; pageNo += 1;} return {'docNo': docNo, 'pageNo': pageNo};
No we have something we can use in the call. We must reference the parameters pageNo and docNo we are returning to use in the next call. In these examples the pre-request is going to run the call previous request call, with that result im memory the PreRequestScript can then run and update values for the main Request. So lets setup the Rest connector for our Data-In:
And here is the output, you can see the docNo and pageNo iterating up by the js script. This is the view of the documents in MongoDB directly using a tool MongoDB Compass:
Here we have successfully implemented a js script in our setup. you can mix and match these where you need it. here is another example you can use in a data-in rest connector, this one uses the script in the pre-request. The PreRequestScript node is also available in the REST Collection Publisher.