Saturday 27 May 2017

GraphQL return null on each fields

I am learning GraphQL through their official website.

The purpose of my graphql on this code is as wrapper my existing REST API. To do that, i already have a rest api with this response:

GET: /people/:id
RESPONSE: 
{
  "person": [
    {
      "id": "1",
      "userName": "mark1",
      "firstName": "Mark",
      "lastName": "Zuckerberg",
      "email": "mark@facebook.com",
      "friends": [
        "/people/2",
        "/people/3"
      ]
    }
  ]
}

and this following code is my graphql schema

import {
    GraphQLList,
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema
} from "graphql";

import fetch from "node-fetch";

const BASE_URL = "http://localhost:5000";

function getPersonByURL(relativeUrl) {
    return fetch(`${BASE_URL}${relativeUrl}`)
        .then(res => res.json())
        .then(json => json.person);
}

const PersonType = new GraphQLObjectType({
    name: "Person",
    type: "Somebody",
    fields: () => ({
        firstName: {
            type: GraphQLString,
            resolve: person => person.firstName
        },
        lastName: {
            type: GraphQLString,
            resolve: person => person.lastName
        },
        email: {
            type: GraphQLString
        },
        id: {
            type: GraphQLString
        },
        userName: {
            type: GraphQLString
        },
        friends: {
            type: new GraphQLList(PersonType),
            resolve: (person) => person.friends.map(getPersonByURL)
        }
    })
});

const QueryType = new GraphQLObjectType({
    name: "Query",
    description: "the root of all queries",
    fields: () => ({
        person: {
            type: PersonType,
            args: {
                id: { type: GraphQLString }
            },
            resolve: (root, args) => getPersonByURL(`/people/${args.id}`)
        }
    })
});

export default new GraphQLSchema({
    query: QueryType
});

when i execute a request using Graphiql it returned null on each field. I believe i made mistake on how i represent my json response or how i accesing my json response from rest api.

These are the request and the result from graphiql

REQUEST
{
  person(id: "1") {
    firstName
  }
}

RESPONSE
{
  "data": {
    "person": {
      "firstName": null
    }
  }
}

Can you please help with any hint?



via lloistborn

No comments:

Post a Comment