所以我对GraphQl还是很陌生,我正尝试从SWAPI获取数据
我在schema.js文件中有此文件可以调用SWAPI(链接和格式均取自https://swapi.co文档)
但是,当我在GraphiQl中测试连接时,它会出现以下错误(也适用于星际飞船):
{
"errors": [
{
"message": "Expected Iterable, but did not find one for field RootQueryType.films.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"films"
]
}
],
"data": {
"films": null
}
}
这是我的schema.js文件:
const axios = require("axios");
const {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLSchema
} = require("graphql");
// Launch Type
const StarshipType = new GraphQLObjectType({
name: "Starship",
fields: () => ({
name: { type: GraphQLString },
model: { type: GraphQLString },
crew: { type: GraphQLString },
passengers: { type: GraphQLString },
film: { type: FilmType }
})
});
// Rocket Type
const FilmType = new GraphQLObjectType({
name: "Film",
fields: () => ({
title: { type: GraphQLString },
director: { type: GraphQLString },
release_date: { type: GraphQLString }
})
});
// Root Query
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
starships: {
type: new GraphQLList(StarshipType),
resolve(parent, args) {
return axios
.get("https://swapi.co/api/starships/")
.then(res => res.data);
}
},
starship: {
type: StarshipType,
args: {
starship_number: { type: GraphQLInt }
},
resolve(parent, args) {
return axios
.get(`https://swapi.co/api/starships/${args.starship_number}`)
.then(res => res.data);
}
},
films: {
type: new GraphQLList(FilmType),
resolve(parent, args) {
return axios.get("https://swapi.co/api/films/").then(res => res.data);
}
},
film: {
type: FilmType,
args: {
id: { type: GraphQLInt }
},
resolve(parent, args) {
return axios
.get(`https://swapi.co/api/films/${args.id}`)
.then(res => res.data);
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
答案 0 :(得分:1)
如果您查看the response from the REST endpoint,它看起来像这样:
The output that i want:
Assume that i only want PERSON tags.
First:0
Last:1
Tag: PERSON
word: I
First: 0
Last: 3
Tag: Bob
word: PERSON
这就是您在解析器中返回的内容。但是,通过将字段的返回类型设为列表,就可以告诉GraphQL使用数组。您应该将解析器更新为:
{
"count": 7,
"next": null,
"previous": null,
"results": [
{
"title": "A New Hope",
"episode_id": 4,
// other fields
}
]
}