最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - graphql query to json query - Stack Overflow

programmeradmin0浏览0评论

Given this GraphQL example, how can I in Javascript do a similar request with JSON?

Using GraphQL the query in the example is:

{
  trip(
    from: {place: "NSR:StopPlace:5533" },
    to: {place:"NSR:StopPlace:5532"}
  ) 
    {
    tripPatterns{duration}
  } 
}

According to the documentation the URL to query is .

Here is what I tried in Javascript:

var url = "";

var tripquery = 
{
    trip: 
    {
        __args: {
            from : {place :"NSR:StopPlace:5533" },
            to : {place :"NSR:StopPlace:5532" }                     
        },
        tripPatterns: {
            duration : true             
        }
    }
};

function jsonQuery(){

    var qry = JSON.stringify(tripquery);
    var url_qry = url + "?query=" + qry;

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", url_qry, true);
    xhttp.setRequestHeader("Content-Type", "application/json");

    xhttp.onreadystatechange = function(){
        console.log("onreadystatechange");
        if(xhttp.readyState === 4 && xhttp.status === 200){
            console.log("json-query-OK");
            console.log(xhttp.responseText);
        }
        else{
            console.log("xhttp.status      : " + xhttp.status);
            console.log("xhttp.statusText  : " + xhttp.statusText);
            console.log("xhttp.readyState  : " + xhttp.readyState);
            console.log("xhttp.responseType: " + xhttp.responseType);
            console.log("xhttp.responseText: " + xhttp.responseText);
            console.log("xhttp.responseURL : " + xhttp.responseURL);
            console.log("json-not-ok");
        }
    };



    xhttp.send();
    console.log("query sent");
}

The code above will result in this output in the console:

query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST ={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 2
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: 
query.js:40 xhttp.responseURL : ={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 3
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : ={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 4
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : ={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok

The __args in the Json object is something I got from an example online, but I haven't really understood it.

Maybe I'm not sure what exactly to search for, but I can't find some good explanation of how to translate this GraphQL query to a JSON object.

Given this GraphQL example, how can I in Javascript do a similar request with JSON?

Using GraphQL the query in the example is:

{
  trip(
    from: {place: "NSR:StopPlace:5533" },
    to: {place:"NSR:StopPlace:5532"}
  ) 
    {
    tripPatterns{duration}
  } 
}

According to the documentation the URL to query is https://api.entur.io/journey-planner/v2/graphql .

Here is what I tried in Javascript:

var url = "https://api.entur.io/journey-planner/v2/graphql";

var tripquery = 
{
    trip: 
    {
        __args: {
            from : {place :"NSR:StopPlace:5533" },
            to : {place :"NSR:StopPlace:5532" }                     
        },
        tripPatterns: {
            duration : true             
        }
    }
};

function jsonQuery(){

    var qry = JSON.stringify(tripquery);
    var url_qry = url + "?query=" + qry;

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", url_qry, true);
    xhttp.setRequestHeader("Content-Type", "application/json");

    xhttp.onreadystatechange = function(){
        console.log("onreadystatechange");
        if(xhttp.readyState === 4 && xhttp.status === 200){
            console.log("json-query-OK");
            console.log(xhttp.responseText);
        }
        else{
            console.log("xhttp.status      : " + xhttp.status);
            console.log("xhttp.statusText  : " + xhttp.statusText);
            console.log("xhttp.readyState  : " + xhttp.readyState);
            console.log("xhttp.responseType: " + xhttp.responseType);
            console.log("xhttp.responseText: " + xhttp.responseText);
            console.log("xhttp.responseURL : " + xhttp.responseURL);
            console.log("json-not-ok");
        }
    };



    xhttp.send();
    console.log("query sent");
}

The code above will result in this output in the console:

query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 2
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: 
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 3
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 4
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok

The __args in the Json object is something I got from an example online, but I haven't really understood it.

Maybe I'm not sure what exactly to search for, but I can't find some good explanation of how to translate this GraphQL query to a JSON object.

Share Improve this question asked Feb 3, 2019 at 11:14 remiremi 1,0574 gold badges20 silver badges49 bronze badges 1
  • The best definition of the wire protocol I've seen is on the graphql site. There is not a standard translation of the GraphQL query syntax into JSON; you pass the query string as a JSON string in a small object wrapper. – David Maze Commented Feb 4, 2019 at 1:11
Add a ment  | 

2 Answers 2

Reset to default 4

I had the same problem and I did it like this:

{
  c_con_tic_PTF(dz: CR, docmanId: 123) {
    docmanId
    dz
    data
  }
}

I tried sending this request as curl mand in OS X How to use CURL in OS X:

curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data '{ "query": "{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }' \

   *my-graphicQL endpoint url*

And I got the response I wanted.

So you want to make something like this from your graphQL query:

{ "query": "{  cz_atlascon_etic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }

And now just send request with JS. If it helps you in any way, this is how my request looked in Java:

HttpRequest mainRequest =
HttpRequest.newBuilder()
.uri(URI.create("my graphQL endpoint"))
.POST(HttpRequest.BodyPublishers.ofString("{ \"query\": \"{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}\" }"))
.build();

One way to do it in Javascript is using the fetch api. Something like this is how I've done it in the past. You can test it out by copying the code below and then pasting it into Chrome Dev Tools and running it.

async function makeGraphQlQuery(urlToResource) {
    const queryObject = {
      query:
        '{ trip( from: {place: "NSR:StopPlace:5533" }, to: {place:"NSR:StopPlace:5532"}) {tripPatterns{duration}} }',
    };
    const response = await fetch(urlToResource, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryObject),
    });

    const json = response.json();

    return json;
}

async function sendAsync() { 
  const res = await makeGraphQlQuery('https://api.entur.io/journey-planner/v2/graphql');
  console.log(res); 
}
sendAsync().catch(err => console.log('Error in query', err));
发布评论

评论列表(0)

  1. 暂无评论