Breaking REST Chains: A Fastify & Mercurius Pathway to GraphQL Glory

Rate this content
Bookmark

Are you tired of wrestling with the limitations of REST APIs? ""Breaking REST Chains: A Fastify & Mercurius Pathway to GraphQL Glory"" is your roadmap to a better way.

Discover how GraphQL solves REST's shortcomings and how to implement it using Fastify and Mercurius. We'll cover:


1. REST limitations that hold back modern apps.

2. GraphQL's game-changing features.

3. Steps to transition using Fastify and Mercurius.


Unlock the full potential of your APIs and break free from REST's constraints. Join us to learn, adapt, and elevate your API game.

Luca Del Puppo
Luca Del Puppo
23 min
04 Apr, 2024

Comments

Sign in or register to post your comment.

Video Summary and Transcription

GraphQL is a versatile query language that allows for the creation of a single server and API that can serve different types of devices. Mercurius is a high-performance GraphQL adapter built on Fastify, offering features such as caching, just-in-time compilation, and support for subscriptions and federation. The Talk demonstrates how to build a GraphQL server using Mercurius Fastify and TypeScript, including the setup of the server, schema, resolvers, and loaders. It highlights the benefits of using GraphQL with TypeScript and how loaders can optimize queries by reducing the number of database calls. The conclusion emphasizes the benefits of building a GraphQL server with Mercurius and provides additional resources for further exploration.

Available in Español

1. Introduction to GraphQL and its Advantages

Short description:

Hello, and welcome to this talk about how to build a GraphQL server using Fastify and Mercurius. GraphQL is a query language that permits you to create a sort of server that serves different kinds of devices. It allows you to use only one server and create only one API to serve different types of devices like desktop, mobile, smartwatch, etc. GraphQL contains a schema where you can define queries, mutations, and subscriptions. Queries retrieve data, mutations update data, and subscriptions allow you to subscribe to events.

Hello, and welcome to this talk about how to build a GraphQL server using Fastify and Mercurius.

So, first of all, let me introduce myself. I'm Luca Del Pupo, a science software developer at Neo4m and a JavaScript and Typescript enthusiast. My free time, I try to run my YouTube channel and also write technical posts for tech people. I also love running, hiking, and pets, but now it's time to jump in the topic of today.

Why GraphQL? So, basically, when we start to work with API, we start with SOA and then move to REST API, but we serve only desktop application or desktop browser application. But nowadays, we have to serve different kinds of devices, like mobile, or smartwatch, and TV. And in some cases, the REST API is a limitation. For instance, every device has its specific user interface and different needs, because the desktop has a big screen, the mobile has a small one, and the smartwatch has a pretty, pretty small one. So, the info that you can show in this kind of device are different. And basically, what happens is that the mobile needs a subset of the data that is needed in the desktop application, and the same is for the smartwatch. And what happens is that basically, the people start to create specific endpoint just to remove the not needed fields, to improve also the performance of the mobile application and the time that the server had to spend to serialize and deserialize the data.

Another problem is that if you are in the browser, your browser has a limitation in time of request in the same moment in parallel, and the number is 10. So, in some scenario, this also is another limitation that you cannot avoid if you are using a REST API. And this is Bill. Bill is a junior backend developer that every day fight with the frontend and the mobile to build a specific endpoint for a single view that they need. Joking apart, REST API is not a mess, but in some scenario, they are not the best solution for your application. And this is why Facebook, now Meta, has created GraphQL.

GraphQL is a query language that permits you to create a sort of server that serves different kind of service device. And if you are a good developer and you build it in the right way, you can use only one server and create only one API and serve different kind of server of device like desktop, mobile, smartwatch, and so on and so on. GraphQL is pretty simple. So basically, it contains a schema. A schema is like your open API, okay? And inside, you can define the queries that is the way to retrieve data from the server. You can define mutation that is the way to update data, delete data, or add data in your server. And there is also subscription. There are also subscriptions that permit you to subscribe to an event. And when something happens in the server, the server will emit this event, and the client maybe can react in some way. I don't know. You can use a mutation to add an item in the car. And when this happens, you can modify the client that is a subscribe to this event.

2. Using Mercurius with GraphQL

Short description:

And maybe you can update the UI in your application. You can use GraphQL to merge microservices and scale your server easily. Mercurius is a high-performance GraphQL adapter built on Fastify. It has many core features and plugins and implements Apollo Federation specifications. Mercurius is open source and under the MITA license. It allows caching, avoids the N plus problem, uses just-in-time compilation, supports subscriptions and federation, and enables batch queries and query persistence.

And maybe you can, in the UI, update the badge of the basket in your application. And in this way, you can scale your server in an easy way. You can also use GraphQL to merge together different microservices. For instance, you can decide to split your server in different microservices, and they can also be used in the SAP IE GraphQL server or in basically different kinds of technology. And then you can update them inside of one GraphQL server and expose only this GraphQL server to the client. And last but not least, remember that when you create this kind of solution, you have to remember that every layer is a cost. It is a cost in terms of money, because resources and memory and resources like memory CPU are not free. But they are a cost also in terms of complexity, because maintaining a layer that has to talk with another part of the application is a cost in terms of complexity.

By the way, why do I love Mercurius? Basically, Mercurius is a high performance GraphQL adapter built on top of Fastify. Basically in 2024, I prefer to use Fastify and Auto Express, because it's a decision made in terms of security and performance. Mercurius has many core features and plugins already ready for production, and you have only to decide which one you want to use and use them in your application in the right way. Out of the box, Mercurius implemented the Apollo Federation specifications that permit you to create different microservices and aggregate them inside of a big microservice. And then Mercurius is open source and is under the MITA license. That means that you can contribute to it, you can open the issue if you want, and you can also fix the problem if you want. And there is a fantastic community that permits Mercurius to continue to release new features or fix some bug fixes if they are.

Which are the core features? So basically Mercurius permits you to cache the parsing and validation of the query, permits you to avoid the N plus problem using loader. You can use a just-in-time compiler to improve the performance of how V8 compiles your function. You can use subscription and federation, as I said before. You can also use a gateway to aggregate different federated servers, or you can also create them. You can enable the batch query and in this way you can use only one HTTP request to have different queries in the result. Or you can also persist some queries because in some cases you can assign an hash to a specific query that you already know and the client can call directly the server using this hash. Mercurius understands that the hash is related to a specific query and returns directly the result. This helps to prevent problem time in reality on parsing and validating data from the request. Because one of the problems is that using GraphQL, one of the problem is that your request can become high in terms of the size of the request.

3. Building a GraphQL Server with Mercurius Fastify

Short description:

Today I showed you how to build a GraphQL server using Mercurius Fastify and TypeScript, resolve the M-plus problem, create a Fastify application, register the server, and start the server on localhost:3000. I also demonstrated how to set up Mercurius for the GraphQL part, import and register Mercurius, and pass the schema, resolver, loader, and enable GraphQL UI for testing.

So now it's time to see the demo. Today I showed you how you can build a GraphQL server using Mercurius Fastify and TypeScript and then how to resolve the M-plus problem. Now let me go to my GraphQL and then jump to Visual Studio Code. So let's start from this part.

This is the entry point of the application. So in this part you have to create your Fastify application, pretty simple. Obviously you have to configure TypeScript and all this kind of stuff, but to run the application you have to create your Fastify application, register the server and start your server, in this case in localhost and in the port of 3000.

Inside of the server we have to register other two stuff. First of all the plugin. In this case the plugin is pretty simple. It's a simple SQLite plugin that permits us to have a memory database and save data inside of the GraphQL using category and post. I also have some prefilled category and post to speed up the demo. Then the second part of the server is the GraphQL part. Inside of this file there is the code of how we can set up Mercurius. Basically we have to import Mercurius and register it inside of our application. We have to pass the schema, the resolver, the loader, and if you want to enable or not GraphQL, GraphQL is a UI to test and see how to test in reality your GraphQL server.

4. Schema, Queries, Mutations, and Resolvers

Short description:

The schema contains the type for category and post, along with an input for creating a new post. Exposed queries include getCategory, getPost, and getPostByCategory, with pagination to prevent performance issues. Mutations exist for creating categories and posts. The resolver implements the schema.

The schema, as you can see here, is a simple string that contains the schema of our application. In this case I describe the type for the category that contains the post and the type for the post that contains the category. And then I also define an input that is the object to create a new post in our server.

So then I have to expose the query and the mutation. As you can see here, there is a type query that contains all the queries that I want to expose outside. In this case, the getCategory, the getCategory, the getPost, the getPost, and the getPostByCategory. When you return a list of data, it's better to add a pagination of them. This prevents a problem on production because maybe the server is busy to deserialize and serialize stuff. Or for instance, the application receives thousands and thousands of data that maybe they need only 10 of them.

And then the same is for the mutation. In this case the mutation, there are two mutations, one for create the category and one for create the post. Pretty simple. Then there are the resolvers. The resolver is the way to implement our schema.

5. Queries, Mutations, and Loaders

Short description:

The query object contains all the queries described in the schema, including getCategory and getting a single category by ID. TypeScript definitions can be generated from the schema, providing type safety for arguments. Pagination and mutations work similarly, with arguments to insert and return data. Loaders allow loading relations between types. The application can be run and tested using GraphiQL, with queries for getCategories and getPost, and mutations to create categories and posts. TypeScript definitions can be generated using the Mercurius Code Gen plugin.

So as you can see, there is an object called query that contains all the queries that I describe in my schema. So as you can see, the getCategory returns the list of the categories. Inside of the third parameter I can have the context. Inside of the context I have the application. And inside the application I can get my plugin for the database and call directly the query.

Then, for instance, I can also get only one category by ID. In the argument, as you can see, I have the ID of the query. Then I also show you how you can generate your TypeScript definition from the schema. But as you can see now, I have all the benefits of TypeScript. So if I try to call this, as you can see, I have the ID. The ID is a possible argument from my query in this case. If I try to call name, as you can see, there is an error because name in this case is declared but it's never used. But basically, name is not a real property of the argument, as you can see. And then, as you can see, it's the same for the pagination but it's the same also for the mutation. So as you can see here, the getCategory has the argument and so on. You can insert the data and return the data.

Last but not least is the loader. The loader is the way to load the relation between the type. For instance, as you can see here, there is the category type and this is the way I can load the post of all of the category. There is the post and this is the way I can return the category of the post. I'll talk more about the loader in the next example when we'll talk about the nplus problem.

So basically, now I can run the application that is already running. We can go back in our GraphiQL and as you can see, we can call the getCategories and have all the results. Or we can also call the getPost and have all the results. Or maybe also create a category or create a post using this new category. Pretty simple. Now, if I go back to Visual Studio Code, last but not least, I want also to show you how you can generate the type. The types are generated using a simple plugin called Mercurius Code Gen. This plugin accepts the application where you have already registered the Mercurius plugin and you need to say the target path for your generated type. In this case, as you can see, I use the generated.ts file and inside of my generated.ts file, I have all the type generated based on my schema.

6. GraphQL with TypeScript and Resolver vs Loader

Short description:

You can use GraphQL with TypeScript and have a single source of the schema. The resolver or loader can be used to load dependencies between types. Using the loader, you can optimize queries and reduce the number of database calls. The loader performs a single query to retrieve all the necessary data.

And in this way, you have all the benefits of GraphQL but also the benefit of using TypeScript and also you have only one single source of the schema. The schema generates the types for you and then also the resolver must be implemented based on your schema.

Okay, now it's time to jump into the second example, the nplus problem. So basically, you can use the resolver or the loader to load the dependency between the type. Basically, what you can do is this. Before I show you the loader, now I want to show you the same stuff but in the resolver. You can use the resolver and describe the category and the post. In this case, as you can see, the category has a post and this is the way how I want to load the post based on the category. Inside of this method, I have the category and using the idea, I can load all the post based on this category. The same is for the post.

If I go back to my terminal and run now the second example, I can call now the category. If I call the category API, as you can see, I called the select category one time but I retrieved the post for each category I need to return. In this case, the API returned the three categories and for each API, I have to call this method. This means that I have to call the database three times. The same is if I call the post, for instance. If I call the list of post, as you can see now, I call the post and then I call the category for the number of elements that I have to return for the post. Pretty simple to understand. This could be a problem on production because as you can imagine, if you have thousands of elements to return, you call the database many, many times. That means you have to return the post and category in different queries. This could be a mess sometimes.

To resolve this problem, you can use the loader that we've already seen before. What happens if I enable the loader? The loader has this different signature. You can define the category type and how to resolve the post. The query, in this case, returns a list of categories. You receive all the categories that you want to return for this query. You can perform this query using only one query to the database. As you can see here, I have only one query using the category ID. Then I have to return a list of objects where every index is perfect. The result for the category in the index 0, the first index of the result is the post for the category in the first index, and the second one is the list of the post for the second category, and so on, and so on. Using this solution, as you can see, what happens is that if I call getCategories, now I call the API for the category, the request for the category once, and also only one time the query to retrieve all the post.

7. Conclusion and Additional Resources

Short description:

Don't hate REST API, they are awesome, but in some scenarios, they are not the best solution. Building a GraphQL server using Mercurius is a piece of cake, and it offers the same benefits as Fastify. Be cautious with your application's layout to understand its behavior. Carefully consider what you expose to frontend developers and add monitoring to track your application's activity. Here are some resources to explore: Fastify and Mercurius documentation, NearForm and backend cafe blogs, NearForm and Adventure in Nordland YouTube channels, and a recommended book on Fastify.

With this, we see all the demo. Now it's time to jump to the conclusion. So now, okay, we can go to the conclusion, and now, okay, I want to say some stuff. The first one is don't hate REST API, they are awesome, but in some scenario, they are not the best solution. Using GraphQL, you can build one and use for everyone. But also, this is not always true, depending on how you build your GraphQL server.

Then, building a GraphQL server using Mercurius is really piece of cake, and don't forget that all the benefits that you have using Fastify, they are also if you are using Mercurius. Be careful with the layout of your application because then understand what happens in your system could be MS sometime. When you build your query, please remember to be careful on what you want to expose to your frontend developer, and give to them only the right power that you want to give to them. Please, don't forget to add a layer of monitoring on your application because it's important to keep track of what happens in your application.

Now I complete my presentation, so if you want, there are the links of the slides on the left and the links of the code on the right. If you want something to read, you can follow these resources. Fastify and Mercurius have documentation. You can go in the NearForm blog or also in the backend cafe blog. If you want something to watch, there are something to watch in our NearForm YouTube channel or also in the Adventure in Nordland YouTube channel that is run by Matteo Colina. If you want something to read as a book, this is a fantastic book about Fastify, and there is also a chapter about Mercurius. That's it.

So, these are my contacts and if you want to chat with me, they are open. You can drop me a message without any problem. If you want to follow me on my YouTube channel, this is the name, and also this is my DevTO account. If you want, I work for NearForm, and we are hiring. If you want to join us, let me know. Last but not least, thank you very much for being here with me today. I hope you enjoyed this talk, and if you have any questions, I'm here. Thank you again and see you soon. Bye bye.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
The Guild has recently released Envelop - a new, modern GraphQL Server Framework and plugin system. In this talk I’ll share a brief overview of Envelop and why you should probably upgrade your existing GraphQL server to it.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
In this talk, we'll look at some of the modern options for building a full-stack React and GraphQL app with strong conventions and how this can be of enormous benefit to you and your team. We'll focus specifically on RedwoodJS, a full stack React framework that is often called 'Ruby on Rails for React'.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
Though GraphQL is declarative, resolvers operate field-by-field, layer-by-layer, often resulting in unnecessary work for your business logic even when using techniques such as DataLoader. In this talk, Benjie will introduce his vision for a new general-purpose GraphQL execution strategy whose holistic approach could lead to significant efficiency and scalability gains for all GraphQL APIs.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.