Friday, July 6, 2018

GraphQL and Apollo Client



I watch the GraphQL with React: The Complete Developers Guide course by Stephen Grider these days.
There are three major sections:

The first section teach you how to use express and graphql-js to build a GraphQL BE server.
He introduce the package json-server which can build a REST server in a super convenient  manner.
Then we can build a GraphQL server in front of the REST server easily without caring the data source.
This section includes how to write the schema to describe the data type , and how to write the resolver to construct the relation between types. We also need to use resolver to provide mutation to allow client to update/delete the data.

The way to write the schema in graphql-js is not that intuitive to me.
const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString }
  }
})
But just like what Stephen said , keep the resolver and the schema in the same place let developer easy to understand what fields this type can provide.

The second section introduce the way to use apollo-client and React to build a GraphQL client .
It includes:
- How to write the query and mutation in apollo-client, and how the response be used in React.
- How to use date.refetch or refetchQueries to trigger the query after mutation is executed.
- How to use optimisticResponse to predict the response to update the UI before getting the response
- Use dataIdFromObject to prevent refetch the API when you already got updated data in the mutation response

In the last section , it introduce how we can use passport-js to provide authentication in GraphQL.
And some gotcha need to be taken care of when you try to redirect the page once user login their account.

Because I already familiar with React , the React part in this course is too easy to me. But it's still quite helpful to have a full understanding to GraphQL. 

apollo-client actually provides a convenient way to access the GraphQL API, especially it cache the data in the query and prevent you to request same query needed in multiple component. 




No comments:

Post a Comment