Search code examples
javascriptjsonconcatenation

Use variable in JSON concatenated payload string


The below payload works if I hardcode the pubblish date, but if I want to use a variable, it breaks, I can't get the correct way of adding a variable in the payload, I can't use template literals as the JS engine is prior to ES6.

var today = new Date();
var publishDate = new Date(new Date().setDate(today.getDate() - 31));
const query = JSON.stringify({query:
               '{' +
               '   all_insight_article(locale: "en-gb"'+
               '     where: {business_unit: {business_unit: {title: "Capital"}, MATCH: ALL}, audience: {MATCH: ALL, audiences: {title: "Management"}} publish_date_gt:'+publishDate+'}'+
               '   ) {items {'+
               '        system {uid publish_details {time} updated_at}'+
               '        absolute_url title subtitle main_image'+
               '        audienceConnection     {edges {node {... on Audiences   {title system {uid}}}}}'+
               '        article_typeConnection {edges {node {... on ArticleType {title}}}}'+
               '        topicsConnection       {edges {node {... on Topics      {title display_name system {uid}}}}}}total}}'
        });

Error:

07/03/2023 14:47:24 js3 []
07/03/2023 14:47:24 js3 INT-150012 The HTTP query returned a 'Unprocessable Entity' type error (422)

Solution

  • Just for completeness, my comment as answer:

    publishDate is still a Date objects but the query expects a string. So you have to quote it and convert it to an ISO String (Date.toISOString) first:

    const query = JSON.stringify({query:
                   '{' +
                   '   all_insight_article(locale: "en-gb"'+
                   '     where: {business_unit: {business_unit: {title: "Capital"}, MATCH: ALL}, audience: {MATCH: ALL, audiences: {title: "Management"}} publish_date_gt:"'+publishDate.toISOString()+'"}'+
                   '   ) {items {'+
                   '        system {uid publish_details {time} updated_at}'+
                   '        absolute_url title subtitle main_image'+
                   '        audienceConnection     {edges {node {... on Audiences   {title system {uid}}}}}'+
                   '        article_typeConnection {edges {node {... on ArticleType {title}}}}'+
                   '        topicsConnection       {edges {node {... on Topics      {title display_name system {uid}}}}}}total}}'
            });