Как получить переменные из массива из внешнего API? - PullRequest
0 голосов
/ 28 марта 2019

Я начинаю с 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);
            }
        },

И это JSON от API:

{
  "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", тестирую с "обозначением", но я просто получаю ошибки вроде:

{
  "errors": [
    {
      "message": "Expected Iterable, but did not find one for field RootQueryType.sentry.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "sentry"
      ]
    }
  ],
  "data": {
    "sentry": null
  }
}

Спасибо, что прочитали:)

1 Ответ

0 голосов
/ 28 марта 2019

В вашем распознавателе RootQuery вы возвращаетесь только с объекта обещания 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
                    });
            }
        },
    }
})

Надеждаэто помогает.

...