【问题标题】:GraphQL Javascript Axios Return null [duplicate]GraphQL Javascript Axios返回null [重复]
【发布时间】:2019-06-24 06:47:06
【问题描述】:

我尝试练习一些 GrahpQL,但我被卡住了...... 我想从 api 列表中获取一个对象,但 grahpql 返回 null。 使用 async/await 没有帮助。 返回所有列表但只有单个元素没有问题。

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

【问题讨论】:

    标签: javascript graphql axios


    【解决方案1】:

    如果您 look at the response 来自 REST 端点,则返回的是一组国家/地区,而不仅仅是一个国家/地区对象。除非字段的类型是列表,否则您的解析器无法返回数组。同样,如果字段的类型是 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];
            }
        },
    

    【讨论】:

    • 哦……我真的是瞎了。非常感谢!
    猜你喜欢
    • 2018-11-29
    • 2017-03-13
    • 2018-07-13
    • 2023-04-08
    • 2019-06-28
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多