Search code examples
facebook-graph-apigraphqlgraphcool

How to define a GraphQL type model that contains complex objects?


I am using the Facebook Graph API's data to get the user info and create my user in the GraphQL service (graphcool).

function createGraphcoolUser(facebookUser) {
    return api.request(`
      mutation {
        createUser(
          facebookUserId: "${facebookUser.id}"
          facebookEmail: "${facebookUser.email}"
          facebookName: "${facebookUser.name}"
          facebookPicture: "${facebookUser.picture}"
        ) {
          id
        }
      }`)
      .then((userMutationResult) => {
        return userMutationResult.createUser.id
      })
}

But ${facebookUser.picture} is an object with nested fields.

{
  "id": "123467890",
  "email": "my@email.ca",
  "name": "John Doe",
  "picture": {
    "data": {
      "url": "https://url.to.picture.jpg"
    }
  }
}

So how do I define it in the type model ?

type User @model {
  # Required system field:
  id: ID! @isUnique # read-only (managed by Graphcool)

  # Optional system fields (remove if not needed):
  createdAt: DateTime! # read-only (managed by Graphcool)
  updatedAt: DateTime! # read-only (managed by Graphcool)

  facebookUserId: String @isUnique
  facebookEmail: String
  facebookName: String
  facebookPicture: ---> HERE <---

  posts: [Post!]! @relation(name: "UserPosts")
}

Solution

  • To answer my own question the info was in the docs (sorry about that):

    We must use Input types

    ... you can also easily pass complex objects. This is particularly valuable in the case of mutations, where you might want to pass in a whole object to be created. In the GraphQL schema language, input types look exactly the same as regular object types, but with the keyword input instead of type ...

    http://graphql.org/learn/schema/#input-types