Swapi GraphQl - не загружать данные в GraphiQl - PullRequest
0 голосов
/ 11 февраля 2019

Итак, я довольно новичок в GraphQl и пытаюсь получить данные из SWAPI

У меня есть это в моем файле schema.js для вызова SWAPI (ссылки и формат взяты из https://swapi.co doucmentation)

Однако, когда я тестирую соединение в 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
});

1 Ответ

0 голосов
/ 11 февраля 2019

Если вы посмотрите на ответ от конечной точки REST , он будет выглядеть примерно так:

{
    "count": 7, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "title": "A New Hope", 
            "episode_id": 4, 
            // other fields
        }
    ]
}

Это то, что вы возвращаете в своем преобразователе.Однако, сделав тип возвращаемого значения для вашего поля List, вы говорите GraphQL ожидать массива.Вы должны обновить свой распознаватель что-то вроде:

films: {
  type: new GraphQLList(FilmType),
  resolve(parent, args) {
    return axios.get("https://swapi.co/api/films/").then(res => res.data.results);
  }
},
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...