Forum Discussion

_anomDiebolt_'s avatar
_anomDiebolt_
Qrew Elite
8 years ago

Service Worker Travel Log - Day 12

Day 12 -  Give Us JSON Response!



You don't know how many times I have heard users and developers ask that the QuickBase API return JSON instead of XML. Apparently this request has just never floated to the top of the QuickBase's feature list. Perhaps we should start a concerted campaign to flood the QuickBase User Voice channel with votes for this feature, stir up a complaint storm in the Community Forum and personally lobby our individual Customer Success Managers.

Well that sounds like a lot of work that could take a long time with an uncertain outcome. How about we just implement the feature our self in a few minutes using our new best friend the Service Worker. Yeah let's do that instead.

As a starting point you might remember that this problem was solved using jQuery:

How To Get JSON From API_DoQuery?
https://haversineconsulting.quickbase.com/db/bgcwm2m4g?a=dr&rid=395

But the problem with this approach is that you have to include a helper function XMLFlatToObj ahead of every place you might want to return JSON from API_DoQuery. It would be a lot more convenient if we could simply specify a parameter &fmt=json to API_DoQuery and return JSON instead of XML but not otherwise alter the native behavior of API_DoQuery if called without this special parameter. Can a Service Worker to that? Yes it can dear reader and it can do a whole lot more.

To see our solution in action visit our application dashboard to register a new Service Worker sw8.js with scope bmtpmup9q (Table #8)

Service Worker Travel Log Dashboard
https://haversineconsulting.quickbase.com/db/bmtpmup9q

Now jump over to Table #8 and press F12 to expose the developer tools console and paste in the following script which makes a call to API_DoQuery using our new parameter value &fmt=json:
var dbid = "bmtpmup9q";
var dbidTable8 = "bmt87ephd";
var apptoken = "bpn2piidu367nrbfezws9dmz6qc6";
$.ajaxSetup({data: {apptoken: apptoken}});
$.get(dbidTable8, {
  act: "API_DoQuery",
  qid: "1",
  options: "num-3",
  fmt: "json"
}).then(function(json) {
  console.log(JSON.stringify(json, null, "  "));
});

Your console session should look like this:




For comparison, if you omit the &fmt=json parameter you will get the normal XML response from API_DoQuery:




Here is a link to our new Service Worker sw8.js and a listing:

Code Page sw8.js
https://haversineconsulting.quickbase.com/db/bmtpmup9q?a=dbpage&pagename=sw8.js

importScripts("https://haversineconsulting.quickbase.com/db/bmss68i2j?a=dbpage&pagename=cheerio.js");

self.addEventListener("install", event => {
  event.waitUntil(self.skipWaiting());
});

self.addEventListener("activate", event => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener("fetch", event => {
  var params = new URLSearchParams(event.request.url);
  if (params.get("act") == "API_DoQuery" && params.get("fmt") == "json") {
    event.respondWith(
      fetch(event.request).then(response => {
        return response.text().then(body => {
          $ = cheerio.load(body);
          var data = [];
          var record = {};
          $("record").each(function() {
            record = {};
            $(this).children().each(function () {
              record[$(this).prop("tagName")] = $(this).text();
            });
            data.push(record);
          })
          var newBody = JSON.stringify({records: data}, null, "  ");
          return new Response(newBody, {headers: {'Content-Type': 'application/json', 'Cache-Control': 'max-age=0'}});
        });
      })
    );
  }
});


You can probably sort out what this new Service Worker is doing but there are a few new things introduced in this code that due to the length of this post we will have to pick up on Day 13 (whenever that occurs).


Next Up: Day 13 - Hip Hip Cheerio!
No RepliesBe the first to reply