0

I tried to practised some GrahpQL and I am stuck... I want to take one object from api list but grahpql returning null. Used async/await doesn't help. There is no problems with returning all list but with single element.

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,
});
Tomy
  • 3
  • 1

1 Answers1

1

If you look at the response coming from the REST endpoint, what's being returned is an array of countries, and not just a single country object. Your resolver cannot return an array unless the type of the field is a List. Similarly, if the type of the field is a List, you cannot return an object in your resolver. This should work:

    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];
        }
    },
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183