【发布时间】:2020-08-24 23:12:14
【问题描述】:
让我们以 SpaceX 发射 api 为例。 如果我使用 REST(在 Node.js 中)发出请求 它看起来像这样:
router.get('https://api.spacexdata.com/v3/launches', function (req, res) {
// What to do with it
})
这将为我获取所有启动数据。
现在,使用 GraphQL,您只需指定所需的字段。
const LaunchType = new GraphQLObjectType({
name: 'Launch',
fields: () => ({
flight_number: { type: GraphQLInt },
mission_name: { type: GraphQLString },
launch_year: { type: GraphQLString },
launch_date_local: { type: GraphQLString },
launch_success: { type: GraphQLBoolean },
rocket: { type: RocketType }
})
})
但是.. 在查询中,您提供与 REST 版本路由相同的路由。
resolve(parent, args) {
return axios
.get('https://api.spacexdata.com/v3/launches')
.then((res) => res.data)
}
那么 GraphQL 请求有何不同?它实际上不是也获取整个数据吗? 它可以在发出请求时以某种方式“遍历”路由吗?
【问题讨论】:
-
我建议您查看apollographql.com/blog/graphql-vs-rest-5d425123e34b 和howtographql.com/basics/1-graphql-is-the-better-rest 以查看区别,但要回答您的问题,不,除非您要求,否则它不会获取所有内容。如果您只对
flight_number或mission_name感兴趣,它只会返回与您要求的完全相同格式的数据。REST将返回所有内容,而您不知道数据的结构。