Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Accelerating Server-Side Development with Fastify

You're reading from  Accelerating Server-Side Development with Fastify

Product type Book
Published in Jun 2023
Publisher Packt
ISBN-13 9781800563582
Pages 406 pages
Edition 1st Edition
Languages
Authors (3):
Manuel Spigolon Manuel Spigolon
Profile icon Manuel Spigolon
Maksim Sinik Maksim Sinik
Profile icon Maksim Sinik
Matteo Collina Matteo Collina
Profile icon Matteo Collina
View More author details

Table of Contents (21) Chapters

Preface 1. Part 1:Fastify Basics
2. Chapter 1: What Is Fastify? 3. Chapter 2: The Plugin System and the Boot Process 4. Chapter 3: Working with Routes 5. Chapter 4: Exploring Hooks 6. Chapter 5: Exploring Validation and Serialization 7. Part 2:Build a Real-World Project
8. Chapter 6: Project Structure and Configuration Management 9. Chapter 7: Building a RESTful API 10. Chapter 8: Authentication, Authorization, and File Handling 11. Chapter 9: Application Testing 12. Chapter 10: Deployment and Process Monitoring for a Healthy Application 13. Chapter 11: Meaningful Application Logging 14. Part 3:Advanced Topics
15. Chapter 12: From a Monolith to Microservices 16. Chapter 13: Performance Assessment and Improvement 17. Chapter 14: Developing a GraphQL API 18. Chapter 15: Type-Safe Fastify 19. Index 20. Other Books You May Enjoy

Developing a GraphQL API

GraphQL is growing in popularity, and every day, more and more services expose their API using this query language. The GQL API interface will help your API consumers to retrieve the minimal set of data they need, benefiting from intuitive and always up-to-date documentation. GraphQL is a first-class citizen in the Fastify ecosystem. Let’s learn how to add GraphQL handlers using a dedicated plugin, avoiding common pitfalls and taking advantage of Fastify’s peculiar architecture.

Here’s the learning path we will cover in this chapter:

  • What is GraphQL?
  • Writing the GQL schema
  • How to make live a GQL schema?
  • How to improve resolver performance?
  • Managing GQL errors

Technical requirements

To complete this chapter successfully, you will need:

All the snippets in this chapter are on GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify/tree/main/Chapter%2014.

What is GraphQL?

GraphQL is a new language that has changed how a web server exposes data and how the client consumes it. Considering our application’s data structure, we could map every data source to a graph of nodes (objects) and edges (relations) to connect them.

Here’s a quick example of a GraphQL query that maps a family and its members:

query {
  family(id: 5) {
    id
    members {
      fullName
      friends {
        fullName
      }
    }
  }
}

By reading our first GraphQL query, we can immediately understand the relation hierarchy. A Family entity has many Person as a members array property. Each item of members may have some Person entities as friends. Commonly, a GQL request string is called a GQL document.

The JSON response to our GQL...

Writing the GQL schema

We must write the GQL schema by using its type system. If we think first about our data, it will be easier to implement it. Let’s try to convert the following diagram to a schema:

Figure 14.2 – Data relation

Figure 14.2 – Data relation

The data relation in Figure 14.2 describes the entities and the relations between them:

  • A family has multiple members
  • A person may have numerous friends that are other family members

So, we can represent these entities into object types by writing the following Schema Definition Language (SDL):

type Family {
  id: ID!
  name: String!
  members: [Person!]!
}
type Person {
  id: ID!
  family: Family!
  fullName: String!
  nickName: String
  friends: [Person!]!
}

The syntax to define a GQL entity is easily readable. We have defined two types. Each type has a PascalCase name and a list of fields surrounded by curly...

How to make live a GQL schema?

In the Writing the GQL Schema section, we wrote the application’s GQL schema. Now, we need to initialize a new npm project. For the sake of simplicity and in order to focus on the GQL logic only, we can build it by running the following code:

mkdir family-gql
cd family-gql/
npm init --yes
npm install fastify@4 mercurius@11

We are ready to create our first file, gql-schema.js. Here, we can just copy-paste the GQL schema we wrote in the previous section:

module.exports = `
# the GQL Schema string
`

Before proceeding further, it is worth mentioning that there are two different ways to define a GQL schema with Node.js:

  • Schema-first: The GQL schema is a string written following the GQL specification
  • Code-first: The GQL schema is generated by an external tool, such as the graphql npm module

In this chapter, we will follow the schema-first implementation as it is the most generic and allows you to get a clear overview of...

How to improve resolver performance?

If we log every SQL query hitting our database when we run the GQL request in Figure 14.4, we will count an impressive amount of 18 queries! To do so, you can update the SQLite plugin configuration to the following:

  const app = Fastify({ logger: { level: 'trace' } })
  await app.register(require('fastify-sqlite'), {
    verbose: true,
    promiseApi: true
  })

With the new configuration, you will be able to see all the SQL executions that have been run during the resolution of the GQL request, and you will see a lot of duplicated queries too:

Figure 14.5 – All SQL queries run by the family resolver

Figure 14.5 – All SQL queries run by the family resolver

This issue is called the N+1 problem, which ruins the service performance and wastes many server resources. For sure, a GraphQL server aims to provide simplicity over complexity. It deprecates the writing of big SQL queries...

Managing GQL errors

The GraphQL specification defines the error’s format. We have seen an example of it in the Implementing our first GQL query resolver section. The common properties are:

  • message: A message description
  • locations: The GraphQL request document’s coordinates that triggered the error
  • path: The response field that encountered the error
  • extensions: Optional field to include custom output properties

With Mercurius, we can customize the message error by throwing or returning an Error object:

  const resolvers = {
    Query: {
      family: async function familyFunc (parent, args,
      context, info) {
        const familyData =
          await context.familyDL.load(args.id)
        if (!familyData) {
  ...

Summary

This chapter has been a dense and intensive boot camp about the GraphQL world. Now, you have a strong base theory to understand the GQL ecosystem and how it works under the hood of every GQL adapter.

We have built a GraphQL server from zero using Fastify and Mercurius. All the knowledge gained from this book’s Chapter 1 is valid because a Fastify application doesn’t have any more secrets for you.

On top of your Fastify knowledge, you are able to define a GQL schema and implement its resolvers. We have solved the N+1 problem and now know the proper steps to manage it and create a fast and reliable application.

You finally have a complete toolkit at your disposal to create great APIs. You are ready to improve your code base even further by adopting TypeScript in the next chapter!

lock icon The rest of the chapter is locked
You have been reading a chapter from
Accelerating Server-Side Development with Fastify
Published in: Jun 2023 Publisher: Packt ISBN-13: 9781800563582
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}