Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 9, 2020 11:39 pm GMT

Intro to GraphQL

Is been around 5 years since GraphQL has been released by the Facebook team, back in 2015. Since then GraphQL just has a raise in popularity. Besides Facebook, companies like Airbnb, Netflix, Coursera, and many more have adopted GraphQL and it seems that have played very well from them not just in productivity but scalability.

What is GrapQL?

  • graphQL is just a query language for fetching data
  • it serves as a specification, not an implementation. That been said, GraphQL does not tell you how it needs to be done, they just provide a specification that you can adapt to.
  • it only exposes a single endpoint to the client that consists of queries, mutations, and subscription
  • the client only queries the data that it needs and that data is returned in the shape that was requested

Schema

we start by defining the schema in the server

type User {   id: ID!   firstName: String!   lastName: String!   """   company that the user is associated with   """   company: Company}type Company {   id: ID!   name: String   """   where is this company located   """   location: String}input UserInput {   firstName: String!   lastName: String!   company: CompanyInput}input CompanyInput {   name: String!   location: String!   userID: ID!}type Query {   """   Fetched the current user   """   currentUser: User}type Mutation {   userCreate(userInput: UserInput!): }

Schemas are the core of the GraphQL server implementation. It describes everything that your API can do. All the queries the client can execute will be run against the scheme definition.

  • Query is the type where all your queries are going to be encapsulated
  • Mutation is the type where yours update-create-delete will happen
  • input is normally used when mutating any data to defined the argument passed

As you have noticed there are """Comment here""" in top of the field, this is how we can write comments on top of the field in the schema.

Resolvers for the schema

After defining the schema we need to define "resolvers". Resolvers basically is a function that knows how to resolve the type that the client is asking for.

const user = { id: 1, firstName: "Henry", lastName: "Arbolaez" };const Query = {  currentUser: (parent, args, context) => {    /**     in the real world you would connect to some database.     return context.db.User.findById(context.userId);    */    return user;  }}

That's how we defined a resolver for the currentUser.

Querying for the current user

query {  currentUser {    id    firstName    lastName  }}

When we query for the current user using the above query, will return the data in the exact shape that was requested

 {   "currentUser": {       "id": 1,       "firstName": "Henry",       "lastName": "Arbolaez",    } }

But let say we want to query for the company of the current user. We would do something like this.

query {  currentUser {    id    firstNmae    lastName    company {      id      name      location    }  }}

When we execute this query company will be returned as null, because there are no resolvers that know how to resolve the company type inside the user type.

We can get around this by resolving the company in the currentUser resolver extending the currentUser resolver above

const user = { id: 1, firstName: "Henry", lastName: "Arbolaez" };const companies = { 1: { id: 1, userID: 1, name: "Course Hero", location: "Redwood City" } };const Query = {  currentUser: (parent, args, context) => {    // const company = context.db.Company.findById(parent.id);    const company = companies[user.id];    return {      ...user,      company,    }  }}

Note There is a problem with this approach. We can not guarantee that whenever the client asks for currentUser it will always ask for the company that the user is associated with. A better approach is to have a resolver for the company type, and only resolve if the client asks for it.

const companies = { 1: { id: 1, userID: 1, name: "Course Hero", location: "Redwood City" } };const Query = {  currentUser: ....,  User: {    company: (parent, args, context) => {      /**        parent: is the user object in this case. Think as the parent, as the Type that is wrapping this resolver. In this case the User type.      */      // return context.db.Company.findById(parent.id)      return companies[parent.id]    }  }}

We added the company resolver under the User type, to match our schema definition. If we were to put the company in the Query type, it wouldn't know what is going to resolve for, due that the schema explicitly said that the company belongs to the User type.

By doing this - that's a quite optimization because now if the client does not ask for the company type when asking for the current user, we're not making any extra request to fetch company and our server is happy!!

Why Graphql?

  • Limit the number of requests that are going to be sent to the server. Due that you can send multiple queries, at the same time in one big query
    • Usually, in REST you will have different RESTful endpoints to do X operation
-- usersGET https://example.com/usersCREATE https://example.com/usersGET https://example.com/users/1DELETE https://example.com/users/1PUT https://example.com/users/1-- companiesGET https://example.com/companiesCREATE https://example.com/companiesGET https://example.com/companies/1DELETE https://example.com/companies/1PUT https://example.com/companies/1-- companies associated with the userGET https://example.com/user/1/companiesGET https://example.com/user/1/companies/1
  • i.e. if we want to fetch all the companies for a given user. We will need to
    1. fetch the user endpoint to get the userId
    2. fetch the companies for the given userId
  • Also in REST i.e. we don't know the shape of the data that is coming back and the type of it.
  • in GraphQL this could be simply be sent to the server as one query while reusing code that is already there, and we would know beforehand what is the shape and type of that data.
query currentUser {  companies {    id    name  }}
  • Improve developer experience and productivity
    • GraphQL is a strong type and has validation
    • There are a lot of tools around GraphQL, that can increase productivity. One of them is the GraphQL Playground, which let you introspect the query before having to write any code.
    • GraphQL will help standardized and simplified complexity in our API's. In the example above about REST, we wouldn't need to worry about creating those many resources.

Wrapping

Hope this intro to GraphQL, have helped understand the basic of what a schema, resolvers and the client request can do for you.

There is quite a few other stuff that we can cover, but with this understanding of GraphQL, you can build a simple graph and deep more into advanced topics.

Here are some resources that I find that are going to be useful:


Original Link: https://dev.to/harbolaez/intro-to-graphql-4a4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To