0

I am writing a GraphQL server in Node.js and Express. I have a JSON file of data and so I am using Axios to query data from that JSON file and pass it to GraphQL query,

const RootQuery = new GraphQLObjectType({
name:'RootQueryType',
fields: {
    holiday: {
        type: Holiday,
        args:{
            date:{type:GraphQLString},
        },
        resolve(parentValue, args) {
            return axios.get('http://localhost:3000/holidays?date='+ args.date).then(res => res.data);
        }
    },

On console.log(res.data), I am getting the data, however, on querying by date from GraphiQL, I am getting

{ "data": { "holiday": { "holiday": null } } }

vardos
  • 334
  • 3
  • 13

1 Answers1

3

I struggled with the exact same issue sometime back. I realized that the data from the REST API / JSON file take some time to be fetched and GraphQL doesn't wait to receive it. So I decided to use Async and Await, and that way, GraphQL waited for the data to be received. In your case, the code would look like:

const RootQuery = new GraphQLObjectType({
name:'RootQueryType',
fields: {
    holiday: {
        type: Holiday,
        args:{
            date:{type:GraphQLString},
        },
        Async resolve(parentValue, args) {
            const results= await axios.get('http://localhost:3000/holidays?date='+ args.date)
           .then(res => res.data);
           return results;
        }
    },
Pang
  • 9,564
  • 146
  • 81
  • 122
Waweru Kamau
  • 1,429
  • 14
  • 20