Formatting GraphQL queries

Apps Script (intermediate level) posted on 17th May 2018


Queries with older JavaScript

If you are using a newer flavour of JavaScript you can do multiline literals using backticks like this

`some text
  and some more text
  and even more text`

This gets concatenated to look like this
"some text\n and some more text\n and even more text"

This makes building a JSON string that needs new lines very straightforward.

GraphQL

I've been using GraphQL with Apps Script for some time, but it can be a real pain to put together the queries, since GraphQL likes new newlines between fields - so if you have a query that needs to look like this
query ($id:ID!)  {
   Customer (id:$id)
   ...customerDetails
   Orders  {
     Consignments  {
       description
       Type  {
         ...typeDetails
       }
     }
   }
 }
fragment typeDetails on Type  {
   description
   Items  {
     name
     value
     quantity
   }
 }
fragment customerDetails on Customer  {
   id
   name
   Address  {
     street
     town
   }
 }

It's quite a struggle to put together without backticks but you can recursively organize arrays or values quite simply. 
  const gql =  
    FidCans.gqlize("query ($id:ID!)", ["Customer (id:$id)","...customerDetails","Orders",["Consignments",["description","Type",["...typeDetails"]]]]) +
    FidCans.gqlize("fragment typeDetails on Type",["description","Items",["name","value","quantity"]]) +
    FidCans.gqlize("fragment customerDetails on Customer",["id","name","Address",["street","town"]]);


And just a few lines of code
var FidCans = (function (ns) {

  ns.gqlize = function (intro, arr) {
    return gqlize (arr, intro) + "\n";
  };
  
  const gqlize = function (arr, str , depth) {
    str = str || "";
    depth = depth || 2;
    // make some spaces
    const spaces  = new Array (depth).slice().join(" ");
    if (Array.isArray(arr)) {
      str += '  {';
      arr.forEach (function (a) {  
        str = gqlize ( a , str, depth+2 );
      });
      str += ('\n' + spaces + '}');
    }
    else {
      str += ( '\n' + spaces + (arr ));
    }

    return str;
  }
  

  return ns;
}) ({});


You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, All formats are available from O'ReillyAmazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.

Comments