GraphQL returning null data from axios [duplicate]

萝らか妹 提交于 2019-11-28 06:41:48

问题


This question already has an answer here:

  • Why does a GraphQL query return null? 1 answer

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 } } }


回答1:


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;
        }
    },


来源:https://stackoverflow.com/questions/48589649/graphql-returning-null-data-from-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!