我正在使用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);
}
}
};