我尝试练习一些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,
});
答案 0 :(得分:0)
如果您look at the response来自REST端点,则返回的是一系列国家/地区,而不仅仅是一个国家/地区对象。除非字段的类型为列表,否则您的解析器无法返回数组。同样,如果字段的类型为列表,则无法在解析器中返回对象。这应该起作用:
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];
}
},