GraphQL Schema和Resolvers组织返回null [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在使用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 /解析器/ index.ts

import PersonResolvers from "./person-resolvers";

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

graphql /人,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);
    }
  }
};
graphql graphql-js
1个回答
0
投票

我设法让它与这个文件夹组织一起工作

对于那些寻找答案的人,你可以在下面查看我的回购

myhendry gql github repo

© www.soinside.com 2019 - 2024. All rights reserved.