我从Apollo GraphQL(使用Axios)开始,当外部API发送数组时,我遇到了问题。 我无法获取对象内部的变量。 我已经尝试了几种方法,但在任何地方都找不到帮助。
const axios = require ('axios');
const {GraphQLObjectType, GraphQLSchema, GraphQLInt,
GraphQLList, GraphQLString } = require('graphql');
const FeedingType = new GraphQLObjectType({
name: 'Feeding',
fields: () => ({
sentry_objects : {type : new GraphQLList(SentryType)},
})
})
//Sentry Objects
const SentryType = new GraphQLObjectType({
name: 'Sentry',
fields: () => ({
designation : {type : GraphQLString},
})
})
//Root Query
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
sentry: {
type: new GraphQLList(SentryType),
resolve(parent, args){
return axios
.get('https://api.nasa.gov/neo/rest/v1/neo/sentry?is_active=true&page=0&size=50&api_key=DEMO_KEY')
.then(res => res.data);
}
},
这就是API中的JSON:
{
"links": {
"next": "https://api.nasa.gov/neo/rest/v1/neo/sentry?is_active=true&page=1&size=50&api_key=DEMO_KEY",
"self": "https://api.nasa.gov/neo/rest/v1/neo/sentry?is_active=true&page=0&size=50&api_key=DEMO_KEY"
},
"page": {
"size": 50,
"total_elements": 908,
"total_pages": 19,
"number": 0
},
"sentry_objects": [
{
"links": {
"near_earth_object_parent": "https://api.nasa.gov/neo/rest/v1/neo/3012393?api_key=DEMO_KEY",
"self": "https://api.nasa.gov/neo/rest/v1/neo/sentry/3012393?api_key=DEMO_KEY"
},
"spkId": "3012393",
"designation": "1979 XB",
"sentryId": "bJ79X00B",
"fullname": "(1979 XB)",
"year_range_min": "2056",
"year_range_max": "2113",
"potential_impacts": "2",
"impact_probability": "7.36e-07",
"v_infinity": "23.9194972826087",
"absolute_magnitude": "18.53",
"estimated_diameter": "0.662",
"palermo_scale_ave": "-2.82",
"Palermo_scale_max": "-3.12",
"torino_scale": "0",
"last_obs": "1979-Dec-15.42951",
"last_obs_jd": "2444222.92951",
"url_nasa_details": "https://cneos.jpl.nasa.gov/sentry/details.html#?des=1979+XB",
"url_orbital_elements": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3012393;orb=1",
"is_active_sentry_object": true,
"average_lunar_distance": 14.2337865829
},
}
试图获取“ sentry_objects”变量,并用“ designation”进行测试,但是我只是遇到类似以下的错误:
{
"errors": [
{
"message": "Expected Iterable, but did not find one for field RootQueryType.sentry.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"sentry"
]
}
],
"data": {
"sentry": null
}
}
感谢您阅读:)
答案 0 :(得分:0)
在您的RootQuery
解析器中,您仅从promise res.data
对象返回,但是您应该返回res.data.sentry_object
对象。
类似的东西:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
sentry: {
type: new GraphQLList(SentryType),
resolve(parent, args) {
return axios
.get('https://api.nasa.gov/neo/rest/v1/neo/sentry?is_active=true&page=0&size=50&api_key=DEMO_KEY')
.then(res => {
// HERE: return the sentry_objects
console.log(res.data.sentry_objects)
return res.data.sentry_objects
});
}
},
}
})
希望有帮助。