0
votes

I'm trying to query a Graphql endpoint with Javascript, and am using this javascript method to create my query:

module.exports = (uid) =>
`{
    rich_text_data_for_uid(uid:"${uid}")
        {
            record_uid
            field_name
            row_number
            value
        }
}`.replace(/\n/g, " ");

This is the valid query in the explorer:

{
    rich_text_data_for_uid(uid:"31D2A75A3254D5EA852581D7006C2BA5")
        {
            record_uid
            field_name
            row_number
            value
        }
}

Note that the JSON below is formatted to make it readable, but it does not have newlines when it's sent to the server (via the replace method call above)

This is what gets sent as the body of my fetch request, and is causing problems (I suspect because of quotes):

{ "query": "{
    rich_text_data_for_uid(uid:"31D2A75A3254D5EA852581D7006C2BA5")
        {
            record_uid
            field_name
            row_number
            value
        }
}"

I have also tried escaping the quotes, and sent this as the payload:

{ "query": "{
    rich_text_data_for_uid(uid:\"31D2A75A3254D5EA852581D7006C2BA5\")
        {
            record_uid
            field_name
            row_number
            value
        }
}"

My Graphql response is always 400:

POST body sent invalid JSON.

Edit When I try with variables, I get an error too:

    {"query":
"{ rich_text_data_for_uid(uid:$uid) {record_uid field_name row_number value } }",
"variables":{"uid":"31D2A75A3254D5EA852581D7006C2BA5"}}

The above says

Variable "$uid" is not defined.

What do I send to pass a String argument to Graphql?

1
do you call fetch() explicitly? add code how you send request - skyboyer
Newlines shouldn't affect the query, you can leave them in the query string if you want. - HRK44
@skyboyer It's not an issue with fetch, I have a dozen other queries that work the same way and they are fine. - mikeb
@HRK44 - Newlines should not, as you say. However, they do, if I remove the .replace(/\n/g, " ") my queries do not work. So, for whatever reason, they matter. - mikeb

1 Answers

1
votes

Instead of deleting the question - I'll post the answer I worked out:

This is the way to make it valid - we have to wrap the query string in a parameterized block that describes the variables we are passing:

module.exports = (uid) =>
`query rd($uid: String) {
    rich_text_data_for_uid(uid:\$uid)
        {
            record_uid
            field_name
            row_number
            pardef
            value
        }
}`.replace(/\n/g, " ");

That, combined with this JSON data, works fine:

const query = JSON.stringify({"query": richTextQueryForUid(uid), "variables": {"uid": uid}})