Search code examples
node.jsexpressgraphqlexpress-graphql

GraphQL with RESTful returning empty response


I am connecting GraphQL with REST endpoints, I confirmed that whenever I am calling http://localhost:3001/graphql it is hitting REST endpoint and it is returning JSON response to GraphQL server, but I am getting an empty response from GraphQL server to GUI as follows:

{
  "data": {
    "merchant": {
      "id": null
    }
  }
}

Query (decoded manually):

http://localhost:3001/graphql?query={
  merchant(id: 1) {
    id
  }
}

Below is how my GraphQLObjectType looks like:

const MerchantType = new GraphQLObjectType({
  name: 'Merchant',
  description: 'Merchant details',
  fields : () => ({
    id : {
      type: GraphQLString // ,
      // resolve: merchant => merchant.id
    },
    email: {type: GraphQLString}, // same name as field in REST response, so resolver is not requested
    mobile: {type: GraphQLString}
  })
});


const QueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'The root of all... queries',
  fields: () => ({
    merchant: {
      type: merchant.MerchantType,
      args: {
        id: {type: new GraphQLNonNull(GraphQLID)},
      },
      resolve: (root, args) => rest.fetchResponseByURL(`merchant/${args.id}/`)
    },
  }),
});

Response from REST endpoint (I also tried with single object in JSON instead of JSON array):

[
  {
    "merchant": {
      "id": "1",
      "email": "[email protected]",
      "mobile": "1234567890"
    }
  }
]

REST call using node-fetch

function fetchResponseByURL(relativeURL) {

  return fetch(`${config.BASE_URL}${relativeURL}`, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    }
  })
  .then(response => {
    if (response.ok) {
      return response.json();
    }
  })
  .catch(error => { console.log('request failed', error); });

}

const rest = {
  fetchResponseByURL
}

export default rest

GitHub: https://github.com/vishrantgupta/graphql
JSON endpoint (dummy): https://api.myjson.com/bins/8lwqk

Edit: Adding node.js tag, may be issue with promise object.


Solution

  • Your fetchResponseByURL function get empty string.

    I think the main problem is that you are using wrong function to get the your JSON string, please try to install request-promise and use it to get your JSON string.

    https://github.com/request/request-promise#readme

    something like

    var rp = require('request-promise');
    function fetchResponseByURL(relativeURL) {
      return rp('https://api.myjson.com/bins/8lwqk')
        .then((html) => {
          const data = JSON.parse(html)
          return data.merchant
        })
        .catch((err) => console.error(err));
      // .catch(error => { console.log('request failed', error); });
    
    }