запрос graphql к запросу json - PullRequest
       6

запрос graphql к запросу json

0 голосов
/ 03 февраля 2019

Учитывая этот GraphQL пример , как я могу в Javascript сделать аналогичный запрос с JSON?

Используя GraphQL, запрос в примере:

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

В соответствии с документацией URL для запроса: https://api.entur.io/journey-planner/v2/graphql.

Вот что я пробовал в 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");
}

Приведенный выше код приведет к выводу в консоли:

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

__args в объекте Json - это то, что я получил из онлайн-примера, но я не совсем понял его.

Может быть, я не уверен, что именноискать, но я не могу найти хорошее объяснение того, как преобразовать этот запрос GraphQL в объект JSON.

Ответы [ 2 ]

0 голосов
/ 26 июля 2019

Один из способов сделать это в Javascript - использовать api fetch.Примерно так я и делал в прошлом.Вы можете проверить его, скопировав приведенный ниже код, а затем вставив его в Chrome Dev Tools и запустив его.

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 голосов
/ 27 мая 2019

У меня была такая же проблема, и я сделал это так:

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

Я попытался отправить этот запрос как команду curl в OS X Как использовать CURL в 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*

И я получил ответ, который хотел.

Итак, вы хотите сделать что-то вроде этого из вашего запроса graphQL:

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

А теперь просто отправьте запрос сJS.Если это поможет вам, вот как мой запрос выглядел в 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...