Luna Tech

Tutorials For Dummies.

GraphQL Intro


Q & A



Q: What problems does GraphQL solve?

A: Under-fetching and over-fetching in consuming REST APIs, especially in an SPA app.

Q: Why under-fetching and over-fetching is an issue?

A: under-fetching means you need to make multiple requests to do your job, while over-fetching means you are getting too much information than you actually need. Both can affect application performance and waste bandwidth.

Objective: use a single request to fetch the exact amount of data we need in our application.

Q: Advantages of adopting GraphQL

A: By using a flexible contract, frontend team collaborate with backend team easily, both teams can work independently and then use GraphQL client and server to hook up the data.

Keypoint: GraphQL acts as a middle man between client and server, it serves the data per client request.

Since the client can control the shape of the data through the request, there’s no longer a need to bother the backend team for shaping a JSON response in a certain way.

GraphQL Frameworks

Q: What is Apollo?

A: GraphQL is an open specification, anyone can create their own implementation of a GraphQL framework based on the specification. Apollo is one of the most popular ones.

Q: Are there any other frameworks?

A: Yes! GraphQL Yoga, Hasura are also implementations of GraphQL specification. Also, GraphQL is not tied to JS language at all.

Q: Which one to use?


Vue and GraphQL

Q: How do these 2 things come together?

A: When client side needs to fetch data from backend, it can either use RESTful API or use GraphQL query language and request from the GraphQL backend server.

Q: How do I use it?

A: The simplest way is just use the built-in fetch function and create a POST request with a query.

fetch("/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "query { currentUser { id } }" }),

Q: How about using a GraphQL client library?

A: It can encapsulate the lower-level details that we’ve put in the fetch function to a nicer API, so it’s easier to work with.

Just like there’s a GraphQL server library for each backend language, there’s at least one GraphQL client library for each frontend framework.