GraphQL从axios返回空数据

时间:2018-02-02 19:30:18

标签: graphql axios express-graphql

我正在Node.js和Express中编写GraphQL服务器。我有一个JSON数据文件,因此我使用Axios查询该JSON文件中的数据并将其传递给GraphQL查询,

opcache.fast_shutdown=0

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); } }, 上,我正在获取数据,但是,从GraphiQL按日期查询,我正在

console.log(res.data)

1 个答案:

答案 0 :(得分:2)

我有时候会遇到完全相同的问题。我意识到REST API / JSON文件中的数据需要一些时间才能获取,而GraphQL不会等待接收它。所以我决定使用Async和Await,这样,GraphQL等待接收数据。在您的情况下,代码看起来像:

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