1. Introduction to GraphQL and its Advantages
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
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
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
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
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
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
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.
Comments