Home Web Development Full Stack Development with Angular and GraphQL

Full Stack Development with Angular and GraphQL

By Ahmed Bouchefra
books-svg-icon Book
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: App Architecture and Development Environment
About this book
GraphQL is an alternative to traditional REST technology for querying Web APIs. Together with Angular and TypeScript, it provides a tech stack option for building future-proof web applications that are robust and maintainable at any scale. This book leverages the potential of cutting-edge technologies like GraphQL and Apollo and helps Angular developers add it to their stack. Starting with introducing full-stack development, you will learn to create a monorepo project with Lerna and NPM Workspaces. You will then learn to configure Node.js-based backend using GraphQL, Express, and Apollo Server. The book will demonstrate how to build professional-looking UIs with Angular Material. It will then show you how to create Web APIs for your frontend with GraphQL. All this in a step-by-step manner. The book covers advanced topics such as local state management, reactive variables, and generating TypeScript types using the GraphQL scheme to develop a scalable codebase. By the end of this book, you'll have the skills you need to be able to build your full-stack application.
Publication date:
March 2022
Publisher
Packt
Pages
390
ISBN
9781800202467

 

Chapter 1: App Architecture and Development Environment

Throughout this book, we'll develop a full stack web application with an Angular frontend, a Node.js backend, and a MySQL database.

As a consequence, in this first chapter, we'll learn about the project's structure and the tools required to develop the application. After that, we'll have our machine ready for development. Specifically, we'll install Node.js alongside npm and MySQL.

Node.js is required for the backend application, which runs a server that exposes a GraphQL API using Express.js, one of the most popular Node frameworks. Node.js is also necessary for development of the frontend application. This is because Angular uses an official command-line interface to initialize the project and scaffold any required artifacts during the application's development.

MySQL will be utilized to store our data but it will not be directly accessible in our code. Rather than that, we will be using an ORM called TypeORM.

In this chapter, we will cover the following topics:

  • The project's architecture and development technologies
  • Installing MySQL
  • Installing and configuring Node.js
 

Technical requirements

This chapter will require access to a computer equipped with an operating system and an internet connection. Because I'll be working with an Ubuntu system, the instructions in this book will be specific to that system. They should also function on any other system that is based on Debian.

 

The architecture and technologies

In this section, we'll learn about the architecture of our application and the technologies that we'll use to develop both the frontend and backend of our application throughout this book.

Let's begin by familiarizing ourselves with the notions of full stack architecture and monorepo repositories (also known as mono-repositories).

Full-stack architecture

We'll be developing a web application that includes both a frontend and a backend, also known as a full stack application. This implies that we will take the job of a full stack developer.

A full stack developer is a web developer who can handle the development of both the frontend (client-side) and backend (server-side) parts of a web development project.

They must be proficient in fundamental technologies such as HTML, JavaScript, and CSS and have some familiarity with others such as TypeScript, Node.js, and database management systems such as MySQL. These technologies may be broadly classified into two types:

  • Client-side languages, frameworks, and tools for developing browser-based applications, including HTML, CSS, JavaScript, TypeScript, and Angular.
  • Languages and tools for the server side, such as Node.js, Python, or PHP, as well as database languages, such as SQL.

To build our full stack application, we'll need two parts:

  • The frontend: This is the application that runs in the client's web browser on the client's machine. Historically, this was accomplished through the use of HTML pages rendered on the server and then returned to the client. However, browsers may now run fully fledged JavaScript applications (also known as client-side apps), which do the majority of the processing on the client's browser and rely on servers just to supply the application's initial files and data. Simply put, the frontend is what presents the user interface with which users interact.
  • The backend: This is the server-side application that will handle HTTP requests, perform some processing logic, and return responses to the browser (HTML and/or JSON data).

We'll use tools such as Lerna to organize our application's code utilizing a monorepo approach. In the context of software development, monorepo simply refers to using a single source code repository (typically version controlled using Git) for all of our applications (the server, client, and any shared libraries).

Let's take a high-level look at how our application will be delivered to the client's machine:

  1. First, the client will make a request by putting your application domain name into the address bar of the browser.
  2. The server will intercept the requests and process the HTML document containing the Angular app.
  3. The client's browser will begin downloading all of the JavaScript and CSS files required to run the Angular application.
  4. Any initial requests to the server for data, such as posts, will be sent by the Angular application and rendered in the user interface.
  5. The other requests will be made to the server after the user begins engaging with the application.

This process provides a high-level overview of how our application operates. We'll go through these stages in greater depth in the next chapters.

After quickly discussing the full stack and monorepo concepts, let's have a look at the technologies and tools we'll be using to build our application.

The development technologies

Every project necessitates the use of a set of technologies and tools. This includes programming languages, command-line interfaces, libraries, and frameworks. We'll be using diverse technologies for both frontend and backend development in our full stack project.

Nowadays, modern development involves using the same tools for both the frontend and the backend. Let's look at these technologies and tools in more detail.

We'll use a recent version of Angular (version 12 at the time of writing) for the frontend, Node.js for the backend, and a set of supporting libraries including Express.js for launching a web server and TypeORM for abstracting database operations.

One of the primary goals of this book is to build a GraphQL API that will be provided by our Express.js server and consumed by our Angular frontend. To abstract all of the low-level APIs necessary to run a web server, we'll utilize Express.js on top of Node.js.

The web server will listen for incoming HTTP requests from the client's browser, which are mostly GraphQL queries for getting data and mutations for creating and updating data.

Following that, we'll look at Node.js and what it is used for.

Running JavaScript on the server with Node.js

What exactly is Node.js? Node.js is a free and open source platform and runtime environment that allows you to run JavaScript on your server and employs an event-driven, non-blocking input/output (I/O) architecture. Ryan Dahl created Node.js in 2009 on top of Google Chrome's JavaScript Engine (V8 Engine).

If you're a seasoned JavaScript developer, you're probably familiar with JavaScript as a programming language used to create dynamic web pages that can only be executed in the client's browser. However, thanks to Node.js, we can now utilize JavaScript to build web apps on both the client (through the browser) and the server.

As you might expect, developers may now utilize a single programming language to create their complete full stack web application rather than utilizing a distinct language for the server, such as PHP or Python, which are just two of the many available alternatives. Node.js, like these languages, may be used to develop the backend of your web applications.

This enables frontend JavaScript developers to begin developing backend apps without learning a new language.

Node.js is used for more than just server-side applications; it's a general-purpose tool for building all kinds of network apps, as well as for building and running frontend desktop tools on the developer's machine. The Angular CLI, for example, is a Node.js-based tool that we'll use to develop and work with our frontend Angular project.

Important Note

Because Node.js is a JavaScript runtime, it may also be used with TypeScript, which is a JavaScript superset that includes object-oriented programming principles and static typing. In this book, we'll develop our backend utilizing Node.js and TypeScript.

Installing packages with npm

Node.js has a large ecosystem as well as a package management tool known as Node Package Manager (npm). It may be used to quickly install packages from a central registry containing thousands of packages built and published by other organizations and developers to tackle common development problems.

You don't have to reinvent the wheel while trying to address the same development difficulties that other developers have previously faced, thanks to the large ecosystem and the npm registry. The npm registry also makes it straightforward to install any package or library with a single command, including well-known libraries such as Angular and Express.js.

On both our frontend and backend projects, we'll use npm to install the necessary tools and libraries, such as Angular, Apollo, and Express.js, among others.

Running a web server with Express.js

As previously stated, Node.js is a platform and runtime environment that exposes a set of low-level APIs that we rarely use directly while building web apps. Instead of developing a lot of sophisticated code or reinventing the wheel, we'll leverage certain libraries created by other developers. Express.js, as we previously stated, is one of these libraries. So, what exactly is it?

Express.js is a popular Node.js web application framework for developing server applications. It's unopinionated, lightweight, and includes all of the fundamental capabilities needed to develop web applications and web APIs.

Express.js saves you from having to deal with low-level Node.js APIs to create servers that receive HTTP requests and respond with HTTP responses. It also makes it simple to implement routing, manage static files, and serve assets.

Tip

Unlike popular frameworks such as Django in Python, which is considered opinionated, Express.js is a flexible framework that does not enforce how you should organize your project.

GraphQL

Now that we know what Node is and that we'll use Express.js to run our backend server, what is GraphQL and where does it fit in this stack?

GraphQL is similar to SQL; however, it is used to query web APIs rather than databases. It is an API specification and query language. It also serves as a runtime for responding to queries in order to get, create, and update data.

Important Note

GraphQL is a newer alternative to REST, which is widely used by developers to create APIs that can be consumed by both desktop and mobile clients.

Facebook introduced GraphQL in 2015 to address some of the shortcomings of REST and other API development methodologies.

For example, with GraphQL, the frontend application may request only the data it requires from the server. This is due to the fact that GraphQL allows you to describe the forms of your data using user-defined types that are formed from fundamental built-in types such as strings and integers.

GraphQL may be used with a variety of network protocols, the most prevalent of which are WebSocket and HTTP.

If you're acquainted with SQL, you'll recognize that it's comparable to how you define the form of your data using tables. If you're acquainted with object-oriented languages, it's also comparable to how you build interfaces and classes to describe real-world objects.

You can send queries that are JSON-like objects that specify the fields you want the server to return with an HTTP response. The following is an example of a query:

post {
  id
  content
  date
}     

If this query is submitted to a GraphQL server with a post type defined with the ID, content, and date attributes, the associated post data will be returned using resolver functions.

A resolver function handles the resolution for data, executes the logic necessary to retrieve data from the database, and returns it to the requesting client.

As previously stated, GraphQL is a standard that is not bound to any programming language or framework. Many popular programming languages, such as Python and JavaScript, have implementations.

It's also not bound to any database system and may be used with any technology stack that includes MySQL, or any database management system, as a database. In our situation, we'll be utilizing it in conjunction with MySQL.

Apollo is one of the GraphQL implementations. So, where does it fit in our technology stack?

Integrating the frontend and backend with Apollo

Apollo, an industry-standard GraphQL implementation for JavaScript, will be used. It consists of a client and a server part, referred to as Apollo Client and Apollo Server, respectively.

Apollo Client is compatible with plain JavaScript as well as recent UI libraries and frameworks (such as React, Angular, and Vue.js), while Apollo Server is compatible with common Node.js frameworks (such as Express.js and Hapi).

We can simply and effortlessly interact between the frontend and backend of our application thanks to Apollo Client and Apollo Server, which eliminates the need for complex data fetching logic.

So, in our Angular frontend, the Apollo Client will provide a layer for sending queries to obtain data as well as mutations for adding, modifying, and removing data from the database. The Apollo Client does not interface with the database directly, but rather with the Apollo Server and Express.js, which operate on top of Node.js.

Saving data with TypeORM and MySQL

The data will be saved in a MySQL database. In development, we'll use a locally installed MySQL server, but in production, you may use a cloud-hosted relational database such as Amazon Relational Database Service (Amazon RDS) or any other service of your choosing.

We picked MySQL as our database management system since it is the most widely used open source relational database in the world, meaning most developers are acquainted with it and may have used it previously in one of their web projects.

It is very easy to install locally on all supported operating systems. It's also simple to set up and scale in production thanks to cloud services such as Amazon RDS and DigitalOcean.

Amazon RDS offers a free tier, and after that is reached, you will only be charged following a pay-as-you-go basis. It will help you to focus on application development rather than database management operations such as backups, monitoring, scalability, and replication.

We will not be using SQL to build tables or query data directly. Instead, we'll use an Object Relational Mapper (ORM) to create database tables and query, insert, and remove data using a high-level programming language rather than SQL. TypeORM, a TypeScript-based ORM, will be used in our case.

Now that we've covered the final major component of our backend, the database, let's have a look at another component of our technological stack: Angular.

Building the frontend with TypeScript and Angular

Google's Angular is an open source client-side framework. It was created from the ground up in TypeScript as a replacement for Angular.js, which was based on plain JavaScript. Angular, along with React and Vue, is one of the three most popular frontend frameworks. It includes the libraries required to build modern frontend web apps for mobile and desktop devices.

We'll create our project with a basic file structure using the official Angular CLI, and we'll organize our client-side TypeScript code using abstractions such as modules, components, and services.

Angular has a client-side router out of the box, allowing us to add routing and navigation to our application. When we start employing these techniques, we'll go over them in greater depth in the coming chapters.

We'll also be integrating our frontend with the GraphQL server, which is built on Apollo Server, by leveraging Apollo Client with Angular.

We will have a technology stack that includes Node.js, MySQL, Express.js, TypeORM, Apollo, and Angular by joining all of these tools.

Now that we've covered the application architecture and technologies, let's get started by installing MySQL and Node.js in our development environment.

 

Installing MySQL

In this section, we'll learn how to install MySQL on our development machine. The instructions for installing MySQL on your computer depend on your operating system, but here, we'll focus on the instructions for Ubuntu.

MySQL is a popular database management system that is also useful for local development since it is simple to install and configure.

The installation process is straightforward; simply update your system's package index, install the mysql-server package, and then execute the accompanying security script.

MySQL is probably already installed on your development machine. If that's the case, you may skip this step.

Important Note

The steps below are exclusively for setting up MySQL on your local machine for development purposes. In production, you must follow the appropriate guides, especially when it comes to securing your database from attacks. You can easily achieve this with cloud services, which provide a managed database that you don't have to manage or secure yourself.

Now, let's get started by running the instructions to install MySQL Server. Open a new command-line interface and run the following commands:

sudo apt-get update
sudo apt-get upgrade -y

These instructions will update your system's package index to the most recent version.

Then, to install MySQL Server, use the following command:

sudo apt-get install mysql-server

Now that we've installed MySQL Server, let's learn how to configure it.

Configuring MySQL Server

After installing MySQL Server, you must execute a security script. Return to the command-line interface and execute the following command:

sudo mysql_secure_installation

You'll be prompted for your root user password; enter it and press Enter.

Next, you'll be presented with a bunch of questions. The first question will be Would you like to set up VALIDATE PASSWORD plugin? This is used to validate passwords and increase security. It evaluates the strength of the password and helps users to create passwords that are sufficiently safe. Because we're on a development machine, this isn't critical, therefore answer with N for no. The following question will ask you to create a password for the MySQL root user. Enter a password of your choice and confirm it.

To select the default answers for the following questions, just type Y and then press Enter:

  • Remove anonymous users?
  • Disallow root login remotely?
  • Remove test database and access to it?
  • Reload privilege tables now?

This will remove some anonymous users as well as a test database and access to it, disable remote root login, and load the privilege tables to guarantee that all previous modifications take effect instantly.

That's all there is to it — you're done! You have successfully installed MySQL Server on your local development machine, which is running Ubuntu. Following that, you'll learn how to verify whether MySQL is running and how to start it if it isn't.

Testing MySQL Server

MySQL should have started automatically after installation. Return to the command-line interface and execute the following command:

systemctl status mysql.service

If it's up and running, you'll see something like this:

 mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: en
   Active: active (running) since Tue 2020-12-08 17:15:40 +01; 48min ago
Main PID: 20416 (mysqld)
    Tasks: 29
   CGroup: /system.slice/mysql.service
           └─20416 /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pi

If MySQL Server is not running, use the following command to start it:

sudo systemctl start mysql

After we've installed MySQL and verified that it's up and running, we'll learn how to install Node.js, which will be required by both our frontend and backend apps.

 

Installing and configuring Node.js

We'll need to install Node.js after installing the MySQL database management system because it's necessary for executing our server code.

We have several options for installing Node.js on our operating system:

  • Node Version Manager (NVM), which you can use to run various versions of Node.js on your development system, acquire information about the available versions, and install any version with a single command
  • The operating system's official package manager, such as APT for Ubuntu, Homebrew for macOS, or Chocolatey for Windows
  • The binaries from the official website at https://nodejs.org/en/download/, which not only provides Windows, macOS, and Linux binaries, but also source code that can be downloaded and compiled

As previously said, we will presume you are running a Debian-based system such as Ubuntu. In this chapter, we'll teach you how to use the first method on an Ubuntu system.

Important Note

If you are not using an Ubuntu or Debian-based system, go to the official website at https://nodejs.org/en/download/package-manager/ and get the necessary instructions to install Node.js on your operating system.

Installing Node.js with nvm

You can install Node.js and npm using nvm instead of your system's native package manager. This utility does not operate at the system level. Instead, it makes use of a distinct folder in your home directory.

This allows you to install several versions of Node.js at the same time and quickly switch between them as needed. In addition, after you've installed nvm, you can quickly install any version of Node.js, old or new, with a single command.

Let's go over the steps:

  1. Return to your command-line interface and run the following command to download the nvm installation script:
    curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh 
  2. Then, use the following command to execute the script:
    bash install.sh

This command will clone the nvm repository under the ~/.nvm folder and update the ~/.profile file as necessary.

  1. To begin utilizing nvm, just source the following file or log out and then log back in:
    source ~/.profile
  2. Using this command, you can quickly retrieve a list of available Node.js versions that you can install:
    nvm ls-remote
  3. We are using v12.22.1 in this book, which you can install using the following command:
    nvm install v12.22.1

This will download the installation binary that is compatible with your operating system and install Node.js together with npm. It will also make this version the default version.

  1. To verify the installed version, use the following command:
    node –v

In our case, we get v12.22.1 printed on the Terminal.

More information on the available commands and how to use them may be found in the official repository at https://github.com/nvm-sh/nvm.

The nvm utility is compatible with Linux, macOS, and Windows Subsystem for Linux (WSL). You may use two unofficial alternatives for Windows:

That's everything – you've configured your development machine to run Node.js, allowing you to install and use Node.js packages such as Express.js to build your backend application, as well as frontend libraries and tools such as Angular CLI.

We'll use npm to install the dependencies for our backend and frontend apps throughout this book.

 

Summary

In this chapter, we learned about the full stack and monorepo architectures of the application we'll be building throughout this book, as well as the technologies we'll be utilizing to build it.

After covering the architecture and technologies, we looked at how to install MySQL on our development machine. Finally, we learned how to install and set up Node.js, which is required by our full stack application's frontend and backend.

This chapter is now complete! We need to build a Node.js server with GraphQL support, to implement the backend, now that we've set up the development environment and installed Node.js. In the following chapter, we'll begin by installing and configuring Express.js, before adding Apollo Server and looking at how to test and debug our GraphQL server.

About the Author
  • Ahmed Bouchefra

    Ahmed Bouchefra is a software developer and technical author with an engineering degree in software development. He is an expert in web development using modern technologies such as Angular and Node.js, along with using traditional technologies such as Python and Django. He's an open sourcerer, developer, and maintainer of multiple open source Angular libraries, such as ngx-qrcode2. He also currently writes tutorials about modern web development on techiediaries and other industry-leading websites.

    Browse publications by this author
Full Stack Development with Angular and GraphQL
Unlock this book and the full library FREE for 7 days
Start now