Swapi GraphQl-不在GraphiQl中获取数据
因此,我对GraphQl相当陌生,我正在尝试从SWAPI获取数据 我在schema.js文件中调用了SWAPI(链接和格式取自doucmentation) 然而,当我在GraphiQl中测试连接时,出现了以下错误(对于星际飞船也是如此): 这是我的schema.js文件:Swapi GraphQl-不在GraphiQl中获取数据,graphql,axios,Graphql,Axios,因此,我对GraphQl相当陌生,我正在尝试从SWAPI获取数据 我在schema.js文件中调用了SWAPI(链接和格式取自doucmentation) 然而,当我在GraphiQl中测试连接时,出现了以下错误(对于星际飞船也是如此): 这是我的schema.js文件: const axios = require("axios"); const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLList, Gra
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
});
如果你看,它看起来像这样:
{
"count": 7,
"next": null,
"previous": null,
"results": [
{
"title": "A New Hope",
"episode_id": 4,
// other fields
}
]
}
这是您在解析器中返回的内容。但是,通过将字段的返回类型设置为列表,您告诉GraphQL需要一个数组。您应该将解析器更新为类似以下内容:
films: {
type: new GraphQLList(FilmType),
resolve(parent, args) {
return axios.get("https://swapi.co/api/films/").then(res => res.data.results);
}
},
谢谢你,丹尼尔!我有一种感觉,我错过了一些简单的事情。我把星际飞船的信息拉得非常好,但是星际飞船中的电影信息显示为空:所以在graphiql中,我问这个。。{星际飞船{姓名、船员、乘客、模型、影片{片名、导演、发行日期}}但影片显示为空。如果我将它与星际飞船分开调用,它会找到信息,尽管RESTAPI不会为每个星际飞船返回一个电影对象数组,只返回电影细节的URL数组。你需要为你的星际飞船类型的
films
字段编写一个解析器。
films: {
type: new GraphQLList(FilmType),
resolve(parent, args) {
return axios.get("https://swapi.co/api/films/").then(res => res.data.results);
}
},