Interacting with the GraphQL API
Interacting with the GraphQL APIChanging the path to where a field is printed in the response [PRO]

Changing the path to where a field is printed in the response [PRO]

This question appeared on Reddit:

I have:

allMdx {
  edges {
    node {
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
      }
    }
  }
}

I need frontmatter.date to be publishedAt:

allMdx {
  edges {
    node {
      publishedAt: frontmatter{date(formatString: "MMMM DD, YYYY")}
    }
  }
}

Problem is, when I do this, I end up with:

{
  "publishedAt": {
    "date": "February 06, 2021"
  }
}

Instead of (which is what I need):

{
  "publishedAt": "February 06, 2021"
}

Is it even possible to alias nested fields like this?

In other words, is it possible to tell the GraphQL server to flatten the shape of the response? And, if so, how to do it?

Here is a solution with Gato GraphQL, making use of the following extensions:

With @export, we can have a first query operation export some result to a variable, and then declare a second query operation that will read this variable and print it on the expected location in the response:

query ExportDate
{
  allMdx {
    edges {
      node {
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
            @export(as: "date")
        }
      }
    }
  }
}
 
query PrintRelocatedDate($date: String)
  @depends(on: "ExportDate")
{
  allMdx {
    edges {
      node {
        publishedAt: _echo(value: $date)
      }
    }
  }
}

...and then executing the query (passing ?operationName=PrintRelocatedDate) will produce this response:

{
  "data": {
    "allMdx": {
      "edges": [
        {
          "frontmatter": {
            "publishedAt": "February 06, 2021"
          },
          "publishedAt": "February 06, 2021"
        }
      ]
    }
  }
}