GraphQL Javascript Axios Return null



我试图练习一些 GrahpQL,但我被卡住了......我想从 api 列表中获取一个对象,但 grahpql 返回空。使用的异步/等待没有帮助。返回所有列表但返回单个元素没有问题。

const axios = require('axios');
const {
    GraphQLObjectType,
    GraphQLInt,
    GraphQLString,
    GraphQLList,
    GraphQLSchema
    } = require('graphql');
// Country basic info
const CountryInfo = new GraphQLObjectType({
    name: "CountryInfo",
    fields: () => ({
        name: { type: GraphQLString },
        capital: { type: GraphQLString },
        population: { type: GraphQLInt },
        flag: { type: GraphQLString },
    })
})
// Root Query
const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        countryList: {
            type: new GraphQLList(CountryInfo),
            resolve(parent, args) {
                return axios.get('https://restcountries.eu/rest/v2/all').then( res => res.data );
            }
        },
        country: {
            type: CountryInfo,
            args: {
                name: { type: GraphQLString }
            },
            async resolve(parent, args) {
               const element = await axios.get(`https://restcountries.eu/rest/v2/name/${args.name}`).then(res => res.data);
               return element;
            }
        },
    },
});
module.exports = new GraphQLSchema({
    query: RootQuery,
});

如果您查看来自 REST 端点的响应,则返回的是一组国家/地区,而不仅仅是单个国家/地区对象。解析程序无法返回数组,除非字段的类型为 List。同样,如果字段的类型是 List,则无法在解析程序中返回对象。这应该有效:

    country: {
        type: CountryInfo,
        args: {
            name: { type: GraphQLString }
        },
        async resolve(parent, args) {
           const elements = await axios.get(`https://restcountries.eu/rest/v2/name/${args.name}`).then(res => res.data);
           return elements[0];
        }
    },

最新更新