I am supporting CandidateX

CandidateX is a startup that focuses on creating inclusion-focused hiring solutions, designed to increase access to job opportunities for underestimated talent. Check them out if you have a few minutes to spare. They need visibility!

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.


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)
   Orders  {
     Consignments  {
       Type  {
fragment typeDetails on Type  {
   Items  {
fragment customerDetails on Customer  {
   Address  {

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;
  }) ({});

For more like this see Google Apps Scripts Snippets

For help and more information join our community, follow the blog or follow me on twitter