GraphQL架构和解析器组织返回null

时间:2018-09-08 08:33:04

标签: graphql graphql-js

我正在使用GraphQL玩星球大战API。使用GraphQL Playground,我获得了针对联合实体的响应的空值。

我相信原因是由于架构和解析器文件的组织。以下是我的代码及其存储的文件,有人可以提供帮助吗?当前设置仅返回“星球大战”角色的名称,但不返回人物/角色下的电影详细信息数组

非常感谢

GQL游乐场

{
  "data": {
    "getPerson": {
      "name": "Obi-Wan Kenobi",
      "films": [
        {
          "title": null,
          "director": null
        }
      ]
    }
  }
}

graphql / schema.ts

import { gql } from "apollo-server-express";

export const typeDefs = gql`
  type Person {
    name: String
    height: String
    mass: String
    homeworld: Planet
    films: [Film]
    vehicles: [Vehicle]
  }

  type Planet {
    name: String
    diameter: String
    climate: String
    terrain: String
    population: String
    films: [Film]
  }

  type Film {
    title: String
    episode_id: Int
    director: String
    producer: String
    releaseDate: String
  }

  type Vehicle {
    name: String
    model: String
    manufacturer: String
    length: String
    crew: String
    passengers: String
    pilots: [Person]
  }

  type Query {
    getPerson(id: Int!): Person
  }

  schema {
    query: Query
  }
`;

graphql / resolvers / index.ts

import PersonResolvers from "./person-resolvers";

export const resolvers = {
  Query: {
    getPerson: PersonResolvers.getPerson
  }
};

graphql / person-resolvers.ts

import fetch from "node-fetch";

export default {
  getPerson: async (_: any, { id }: { id: string }) => {
    try {
      const res = await fetch(`https://swapi.co/api/people/${id}/`);
      return res.json();
    } catch (error) {
      throw error;
    }
  },
  Person: {
    films: (person: any) => {
      const promises = person.films.map(async (url: string) => {
        const res = await fetch(url);
        return res.json();
      });
      return Promise.all(promises);
    },
    vehicles: (person: any) => {
      const promises = person.vehicles.map(async (url: string) => {
        const res = await fetch(url);
        return res.json();
      });

      return Promise.all(promises);
    }
  },
  Vehicle: {
    pilots: (vehicle: any) => {
      const promises = vehicle.pilots.map(async (url: string) => {
        const res = await fetch(url);
        return res.json();
      });

      return Promise.all(promises);
    }
  }
};

1 个答案:

答案 0 :(得分:0)

我设法使它与此文件夹组织一起工作

对于那些寻求答案的人,您可以在下面查看我的回购邮件

myhendry gql github repo