0

i am toying with the Star Wars API using GraphQL. Using GraphQL Playground, i get null values for the response for the joint entities.

I believe the reason is because of the organization of my schema and resolver files. Below are my codes and the files they are stored in, anyone can help? The current setup only returns the name of the Star Wars character but doesn't return the array of films details under the person/character

Thanks a lot

GQL Playground

{
  "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);
    }
  }
};
Hendry Lim
  • 1,929
  • 2
  • 21
  • 45

1 Answers1

0

I have managed to get it work with this folder organization

For those looking for answers, u can check out my repo below

myhendry gql github repo

Hendry Lim
  • 1,929
  • 2
  • 21
  • 45