Category Archives: blog

Understanding GraphQL – Part 1

Introduction

In this blog, I am not going to explain, why you should use GraphQL or when you should use GraphQL. Answering those questions requires architect level knowledge, which I don’t possess at this very moment. I am just assuming, you have decided to use GraphQL in your project (either by force or by choice) and need a better understanding of it. As I have been using GraphQL recently, I have fallen into some common traps because of my lack of understanding of GraphQL. I don’t want you to make the same mistakes. Having said that let’s start our journey to understand what is GraphQL. We will learn about GraphQL and basic types for creating GraphQL schema in this blog.

So what is GraphQL

GraphQL is a query language for your API, not for the database. It is database agnostic. It can be used with any database. GraphQL allows clients to query data from multiple sources in the API at one request and it allows clients to define which part of the data the client needed. Whilst providing you with such flexibility, GraphQL has some problems as well, for instance, the famous N+1 problem. Before we jump into that, let’s discuss some common terminology used in GraphQL.

Schema

Schema is the blueprint for your GraphQL service. Before you can start using that, you have to define some schema using the GraphQL schema definition language. It has a very simple syntax for defining schema. Once you understand the basic terms and usage you will be able to create schemas in no time. During schema design, we define types and their requirements. We can Query the data from API using those types and perform Mutation on those types as well. So, what is a Query and a Mutation?

Query

As per the GraphQL documentation,

Every GraphQL service has a query type and may or may not have a mutation type. These types are the same as a regular object type, but they are special because they define the entry point of every GraphQL query.

When we send a request to a GraphQL service to query some data, we mention the type of data that we want in response and the necessary fields inside that type.Let’s say you have a type called User and it has some fields like id, name, avatarLink, dateOfBirth, location, etc. When you want to show the users list in client-side, you only need the user’s name and avatarLink. So you can perform a query as follows,

{
  user {
    name
    avatarLink
  }
}

And the response will look like,

{
    'data': {
        'user': {
            'name': 'John Snow',
            'avatarLink': 'https://....'
         }       
    }
}

To define this query in the schema, we need to write,

type Query {
    user(id: ID!): User
    ...     # other query definition.
}

Here we have defined the Query type in our schema. That means, clients can query for a user by some id and in response, they will get the respective User object. The ! mark after ID means that id field is required. We can not query for a user without the id field. An explanation of what ID is or what User will be available in a future section. So in short, we can say that by defining the query type, we create a portal to get different data from the client-side. Remember that every schema must have a query type defined and/or a mutation type defined.

Mutation

The mutation is another important type of schema definition. If you want to modify some data in the data store of your service using GraphQL, you need to define a mutation type. You can consider this as a union of post/put/delete http request type. Whenever we want to create/update/delete data, we need to perform a mutation. A mutation can be defined as,

type Mutation {
    createUser(name: String!, avatarLink: String, dateOfBirth: String, location: String): User
    ... # Other mutations
}

In the mutation above, we defined a mutation that will take a name, avatarLink, dateOfBirth, location as input, and then in response returns a User object. By now, you might already understand that the name field is a required parameters and other fields are not. We can send a mutation request from client side like this,

What you will get in response is something like this,

{
    'data': {
        'createUser': {
            'name': 'Ned Stark',
            'location': null,
            'avatarLink': null,
         }
    }
}

Now as you understand the two most important types in GraphQL schema, let’s get back to the understanding of schema. Schema is a definition of different types of data that is used throughout your application. You can think of it as the data model, for example, what your data are constructed with, which data a client can request or mutate. In order to define a type, we have some primary building blocks in GraphQL. They are called Scalar types. All complex types boil down to a Scalar at the end. There are 5 Scalar types by default in GraphQL. As per the GraphQL documentation they are,

  • Int: A signed 32‐bit integer.
  • Float: A signed double-precision floating-point value.
  • String: A UTF‐8 character sequence.
  • Boolean: true or false.
  • ID: The ID scalar type represents a unique identifier, often used to
  • refetch an object or as the key for a cache. The ID type is serialized
  • in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.

Besides these scalar types, we can define our own Scalar types if needed. You can define custom scalars as follows:

scalar Date

How that type should be serialized, deserialized, and validated is up to your implementation. For example, you could specify that the Date type should always be serialized into an integer timestamp, and your client should know to expect that format for any date fields.

Enums: Enums are special type of Scalar. It has a very specific number of allowed values. We have to define those values during the definition of the Enums itself. For example:

enum PrivacyType {
  Public
  Private
}

If you define some field to be of PrivacyType, then you won’t be able to set any values other than Public or Private for that field. We always expect the value to be either Public or Private.

Conclusion

So far, we have learned about GraphQL Schema definition language, basic types, mutation and query types. Now you will be able to create a basic schema with mutations and queries. In the next part we will learn how to create custom types and advanced feature of GraphQL, such as, Fragments, annotations, Union, Interface.

Leveraging these feature, you will be able to create a more complex schema. If you find any mistake in the above section or you have some suggestion feel free to share. Feedbacks are always welcome. You can contact me via Twitter, Linkedin.

Spending Weekend with GraphQL

Have you ever experienced an itch you just can’t scratch? If yes, then you will feel my pain. A few days back, everything was fine, I was happily writing code(!) and doing standup meetings regularly. Just before the weekend, my boss called me and shared this problem with me.

We were creating a page upon form submission. Then update the cache in the client-side with that newly created page and redirecting to that page. Everything was going well. But after the first page is created and the cache is updated, the Query was returning an empty {}. No errors, nothing, just an empty object.

At first, I thought this was just a simple problem with a state management issue. I spent the next two days trying to identify the underlying problem. During that time, I have re-written that entire component from scratch (blaming the component is always the first task :p ), passed different callbacks methods to different child components of that parent component, and some voodoo stuff. Nothing seems to work. Always the same {} empty object.

I was pulling my hair off and at times I was considering quitting my job. But I couldn’t get it out of my head.

What an irony of fate, just after my weekend was over and I was preparing for bed, I thought, okay let’s try 30 more minutes in the problem. After some digging, through pure serendipity, I found this link. The problem was that, if you try to fetch partial data from graphql API using apollo-graphql and try to updates the cache with that partial data, the query will fail silently without throwing any errors. That is why I hate failing silently. Failing should be done with flying colors in my opinion.

At last, I found out that, we have added some new fields in different PR and it was merged in our dev branch. As usual, I pulled that branch into my current branch and was unaware of the new field in the query. That little(!!!) difference F****D my whole weekend :(. But man, the moment I realized the issue, that eureka moment, it was awesome. I think we all love this job because of these eureka moments. I was happier than ever. I almost forgot that I lost 2 days of break and have to start working from tomorrow. With the massive dopamine rush in my brain, I started writing this article without sleeping. 🙂

The first step towards Infinity

Photo by Reddgio on Unsplash

Recently I have started doing a project where I intend to visualize Quine-McCluskey Algorithm . I have done working on a minimal version of it. Though it is not at all what I thought it would be. When I was working on the idea I thought I will visualize this algorithm with awes0me animation and artwork. But after finishing the project it looked so simple that I was hesitating to upload the project on github. Now I am going to tell you what I have learnt doing this project.

1. I am a terrible UI/UX designer

Thats true. I am a terrible UI/UX designer. I don’t have a speakable amount of color sense. I don’t understand which color will go with which one. And while doing code I didn’t think about the user. How much they will like it or how much they will understand the navigation system.

2. I am not good at code optimization

Yes, my code is what they called is spaghetti code. Even I don’t understand them when I looked at the code after only 2 days. And there is no comment. Than I understood why my teacher and mentors asking me for commenting code. Thought that after doing the code I will comment them out. But with all the joy of finishing the project I forgot to do commenting. And there is no documentation of my code. I can’t do documentation. Actually I knew that I won’t be able to document my code. I need to learn documenting my code.

You might think why the hell this person saying all the things that he can’t do or bad at. Because my friend I realize everyone has to start somewhere. You can not born with all the knowledge that needed to do this works. So, at first if you are facing this problem don’t get frustrated. This is ok if you don’t understand what to comment or what to document or why red is a bad color and simple whitish color is good. Everything will be alright. Now here is the true purpose of this post. I am telling you the problem I am facing while coding without mentor. If you have any suggestion for me please leave a comment.

Now One Good Thing

I realized that it is easy to code once you figured it out in your mind. Once you finished with your strategy of tackling a problem start coding. It will take no time. The project I am talking about I have done this within hours after 4–5 days of thinking. I know you are laughing. Thinking wow so much bragging. Yes it is right. But from my situation I consider it worth bragging. i don’t know either javascript or HTML,CSS well enough. And I have written this project without any framework. All raw code. Stackoverflow helped a lot.

Here is a live version of the project.

Any suggestion (about UI/UX or how to animate the algorithm process) and pull request(with modified code, readable code, documentaion , code for visualising new algorithm) is welcome.

I am willing to make this small project a big one. I want to visualize as much algorithm as I can.

If you have any suggestion for me or for this project feel free to comment.