Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

Understanding GraphQL with a Real Project

GraphQL is a powerful query language designed to work seamlessly with APIs, allowing them to efficiently interact with your existing data. Unlike traditional REST APIs, GraphQL provides a comprehensive overview of the data in your API, making it easy to request only the exact data you need and nothing more. This not only streamlines your API requests but also makes it easier to optimize and improve your APIs when necessary. Additionally, GraphQL comes equipped with powerful developer tools to further enhance your development experience.

In this chapter, we’ll delve into the practical application of GraphQL by building a basic login and user registration system for a real-world project. By exploring how GraphQL can be utilized in this context, you’ll gain a comprehensive understanding of the language and be able to apply it effectively in your own projects.

We will cover the following topics in this chapter:

    ...

Understanding GraphQL with a Real Project

GraphQL is a powerful query language designed to work seamlessly with APIs, allowing them to efficiently interact with your existing data. Unlike traditional REST APIs, GraphQL provides a comprehensive overview of the data in your API, making it easy to request only the exact data you need and nothing more. This not only streamlines your API requests but also makes it easier to optimize and improve your APIs when necessary. Additionally, GraphQL comes equipped with powerful developer tools to further enhance your development experience.

In this chapter, we’ll delve into the practical application of GraphQL by building a basic login and user registration system for a real-world project. By exploring how GraphQL can be utilized in this context, you’ll gain a comprehensive understanding of the language and be able to apply it effectively in your own projects.

We will cover the following topics in this chapter:

    ...

Technical requirements

To complete this chapter, you will need the following:

You can find the code for this chapter in this book’s GitHub repository at https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter13.

Building a backend login system using PostgreSQL, Apollo Server, GraphQL, Sequelize, and JSON Web Tokens

In this section, we will be building a backend login system using PostgreSQL, Apollo Server, GraphQL, Sequelize, and JSON Web Tokens (JWTs). We will utilize PostgreSQL for data storage, Sequelize to perform database operations, Apollo Server to create a GraphQL API, GraphQL to shape our API, and JWTs for user authentication and authorization. Whether you are a beginner or an experienced developer, this guide will offer a comprehensive understanding of how to integrate these technologies into a robust and secure backend login system. Let us dive in.

Installing PostgreSQL

For this example, we will use a PostgreSQL database, so you’ll need to install PostgreSQL to be able to run this project on your machine.

PostgreSQL is an excellent choice for our database. Why? It excels in keeping data secure and well organized, even in the event of an unexpected issue. It has the capability to handle various types of data, which proves to be extremely convenient. Additionally, PostgreSQL is extensible, enabling it to go beyond the basics. It operates efficiently and can manage a substantial number of users concurrently.

Moreover, it boasts robust security features that ensure the protection of our data. Being an open-source platform, it is not only free but also benefits from a large community actively working toward its improvement. If you have prior experience with other databases, PostgreSQL is easy to comprehend, as it adheres to the same standards. Furthermore, it can handle considerable amounts of data and accommodate...

Creating our backend project

First, you need to create a backend directory in your GraphQL project (graphql/backend). After that, let’s review the huge list of NPM packages you will need to install (focusing on the most relevant):

npm init --yes
npm install @apollo/server@4.7.3 @contentpi/lib@1.0.10 @graphql-tools/load-files@7.0.0 @graphql-tools/merge@9.0.0 @graphql-tools/schema@10.0.0 body-parser@1.20.2 cors@2.8.5 dotenv@16.1.4 express@4.18.2 graphql-middleware@6.1.34 graphql-tag@2.12.6 jsonwebtoken@9.0.0 pg@8.11.0 pg-hstore@2.3.4 pm2@5.3.0 sequelize@6.32.0 ts-node@10.9.1
npm install --save-dev prettier@2.8.8 ts-node-dev@2.0.0 typescript@5.1.3 eslint@8.42.0 @types/jsonwebtoken@9.0.2 @types/cors@2.8.13

Please note that some readers of my last book encountered issues with certain code that did not work as intended. This is due to updates to package versions since the time of writing.

To ensure that the code in this book functions correctly, I have specified the...

Configuring Apollo Server

Apollo Server is a highly popular open-source library for working with GraphQL, both as a server and client. With extensive documentation and straightforward implementation, it has become a go-to choice for many developers. Its intuitive interface and flexible architecture make it easy to customize and adapt to your specific needs, while its robust features and reliable performance ensure seamless integration with your existing code base. Whether you’re a seasoned developer or new to GraphQL, Apollo Server is a powerful tool that can help you take your projects to the next level.

The following diagram explains how Apollo Server works in the client and the server:

Diagram  Description automatically generated

Figure 13.2: Apollo Server

Apollo Server facilitates efficient communication between your app or website and the associated database. By utilizing GraphQL, it enables the frontend part of your app to request specific data from the backend in a single operation, resulting in...

Defining our GraphQL types, queries, and mutations

Now that you have created your Apollo Server instance, the next step is to create your GraphQL types. When setting up a GraphQL server like Apollo, creating GraphQL types is crucial. These types ensure that the data returned from your API is reliable and conforms to the expected structure. They act as a helpful reference for available data and its expected format. By using types, your application can precisely request the required data, resulting in faster execution and reduced data consumption. Additionally, types help maintain data consistency, resulting in a robust, comprehensible, and efficient API.

Scalar types

The first thing you need to do is define your scalar types at /backend/src/graphql/types/Scalar.ts:

import gql from 'graphql-tag'
export default gql`
  scalar UUID
  scalar Datetime
  scalar JSON

Now, let’s create our User type (backend/src/graphql/types/User.ts):

import gql from ...

Creating our resolvers

A resolver is a function that’s responsible for generating data for a field in your GraphQL schema. It can normally generate the data in any way you want, in that it can fetch data from a database or by using a third-party API.

To create our user resolvers, you need to create a file called /backend/src/graphql/resolvers/user.ts. Let’s create a skeleton of what our resolver should look like. Here, we need to specify the functions that are defined under Query and Mutation in our GraphQL schema. So, your resolver should look like this:

export default {
  Query: {
    getUsers: () => {},
    getUser: () => {}
  },
  Mutation: {
    createUser: () => {},
    login: () => {}
  }
}

As you can see, we return an object with two main nodes called Query and Mutation, and we map the queries and the mutations we defined in our GraphQL schema (the User.ts file). Of course, we need to make some changes to receive some parameters and return...

Using the Sequelize ORM

Sequelize is a popular ORM library for Node.js. It enables developers to interact with databases like MySQL, PostgreSQL, SQLite, and Microsoft SQL Server by abstracting the underlying SQL commands into higher-level, easy-to-use JavaScript objects and methods.

Using Sequelize, developers can perform database operations like creating, updating, deleting, and querying records without having to write raw SQL queries. Sequelize also helps with defining data models, managing associations between tables, and handling database migrations.

Some key features of Sequelize ORM include:

  • Model definition: Sequelize allows you to define models with their attributes, data types, and constraints, which map to tables in the underlying database.
  • Associations: You can easily define relationships between models, such as one-to-one, one-to-many, and many-to-many, which map to foreign key constraints in the database.
  • Querying: Sequelize provides a robust...

Authentication functions

Step by step, we are putting all the puzzle pieces together. Now, let’s look at the authentication functions we will use to validate whether a user is connected or not and get the user’s data. For this, we need to use JWTs.

JWT is an open standard outlined in RFC 7519 (https://tools.ietf.org/html/rfc7519). It serves as a valuable tool to transmit information between parties as a JSON object. One of the primary advantages of JWTs is their digital signature, which allows them to be easily verified and trusted. The token is signed using the HMAC algorithm and a secret or a public key pair using RSA or ECDSA, ensuring that it remains secure and tamper-proof. This makes JWTs a reliable choice for authentication and authorization purposes in a wide range of applications.

Creating JWT functions

Let’s create some functions that will help verify a JWT and get the user data. For this, we need to create the jwtVerify, getUserData, and...

Running our project for the first time

Next up, we’re going to start our project for the first time. If we’ve done everything right, we’ll see our Users table being set up and our Apollo Server will start running.

In this part, we’ll cover how to start our project. After that, we’ll explore how to use our GraphQL API. We’ll learn about testing queries, which allow us to retrieve data, and mutations, which enable us to modify data. We’ll also discuss validations, which are checks to ensure the correctness of our data. Lastly, we’ll delve into the process of user login. Let’s get started!

If you followed the previous sections correctly and run the npm run dev command, you should be able to see that the Users table has been created and that Apollo Server is running on port 4000:

A picture containing background pattern  Description automatically generated

Figure 13.3: Running our project for the first time

Now, let’s say that you want to modify your user model and change...

Building a frontend login system with Apollo Client

In the previous section, we learned how to build the backend for a login system using Apollo Server to create our GraphQL queries and mutations. You are probably thinking, Great, I have the backend working, but how can I use this on the frontend? And you’re right: I always like to explain things with full examples and not just show basic things, even if this will take longer to do. So let’s get started!

You can find the code for the example in this section at https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter13/graphql/frontend.

Configuring Webpack 5

Instead of using a vite project, we will configure a React project from scratch using Webpack 5 and Node.js.

The first thing we need to do is create the frontend directory and install all the packages inside. To do this, we will execute the following commands:

npm init --yes
npm install @apollo...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
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.
undefined
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 €14.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán