0

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

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

在 上console.log(res.data),我正在获取数据,但是,在从 GraphiQL 按日期查询时,我得到了

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

4

1 回答 1

3

我曾经为完全相同的问题而苦苦挣扎。我意识到来自 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;
        }
    },
于 2018-04-18T06:08:04.107 回答