Full Stack Development with Angular and GraphQL - Ahmed Bouchefra - E-Book

Full Stack Development with Angular and GraphQL E-Book

Ahmed Bouchefra

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 352

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Full Stack Development with Angular and GraphQL

Learn to build scalable monorepo and a complete Angular app using Apollo, Lerna, and GraphQL

Ahmed Bouchefra

BIRMINGHAM—MUMBAI

Full Stack Development with Angular and GraphQL

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Bhavya Rao

Senior Editor: Hayden Edwards

Content Development Editor: Abhishek Jadhav

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Ajesh Devavaram

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Shankar Kalbhor

Marketing Coordinator: Anamika Singh

First published: February 2022

Production reference: 1280222

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80020-246-7

www.packt.com

To my mother, and to the memory of my father.

– Ahmed Bouchefra

Contributors

About the author

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 sourcer, developer, and maintainer of multiple open source Angular libraries, such as ngx-qrcode2. He also currently writes tutorials about modern web development on techiediaries.com and other industry-leading websites.

About the reviewer

Peter Eijgermans is a long-time software developer and an adventurous and passionate Codesmith frontend developer at Ordina Netherlands. He likes to travel around the world on his bike, always searching for the unexpected and unknown. As part of his job, he tries out the latest techniques and frameworks. He loves to share his experience by speaking at conferences all over the world and writing for the Dutch Java magazine and DZone. He believes that frontend developers are the spiders in the web to bring the user, the project team, and the product together.

I would like to thank the following colleagues for their help in reviewing the book:

Corneel Eijsbouts

Jeroen Verhoeven

Michael Awad

Table of Contents

Preface

Part 1: Setting Up the Development Environment, GraphQL Server, and Database

Chapter 1: App Architecture and Development Environment

Technical requirements

The architecture and technologies

Full-stack architecture

The development technologies

Running JavaScript on the server with Node.js

Installing packages with npm

Running a web server with Express.js

GraphQL

Integrating the frontend and backend with Apollo

Saving data with TypeORM and MySQL

Building the frontend with TypeScript and Angular

Installing MySQL

Configuring MySQL Server

Testing MySQL Server

Installing and configuring Node.js

Installing Node.js with nvm

Summary

Chapter 2: Setting Up GraphQL with Node.js, Express.js, and Apollo

Technical requirements

Setting up a monorepo project

Initializing our server project

Generating a package.json file

Installing Express.js and development dependencies

Creating the server

Watching and recompiling our code

Creating a GraphQL API

Installing the necessary libraries

Exposing a simple GraphQL API

Sending queries with Apollo Studio

Creating a GraphQL schema for our social network

Mocking our GraphQL API

Linking the mocked data

Configuring CORS

Summary

Chapter 3: Connecting the Database with TypeORM

Technical requirements

Creating a MySQL user and database

Setting up TypeORM and MySQL

Creating TypeORM entities

Seeding test data

Using Apollo with TypeORM

Summary

Chapter 4: Implementing Authentication and Image Uploads with Apollo Server

Technical requirements

What's JWT?

Implementing authentication

Protecting GraphQL queries and mutations

Implementing image uploads

Assignments

Summary

Chapter 5: Adding Realtime Support with Apollo Server

Technical requirements

Understanding GraphQL subscriptions

Implementing GraphQL subscriptions

Implementing JWT authentication with subscriptions

Summary

Part 2: Building the Angular Frontend with Realtime Support

Chapter 6: Angular Application Architecture and Routing

Technical requirements

Installing the Angular CLI

Angular CLI commands

Initializing the Angular project

Understanding the application architecture

What's a module?

What's a component?

Understanding services and dependency injection

Creating modules, services, and components

Creating modules

Creating components and services

Understanding Angular routing

How the Angular Router works

The <base href> tag

The routing modules

The router outlet

Importing the routing module

Understanding and adding routes

Route-matching strategies

Route parameters

Adding routes

Adding navigation

Debugging Angular applications

Adding Angular Material

Summary

Chapter 7: Adding User Search Functionality

Technical requirements

Introducing and installing Apollo Client

Importing Angular Material components

Signing up and logging users in

Defining GraphQL documents

Defining types for user authentication

Defining Apollo services

Implementing the user authentication service

Building and styling the signup UI

Building and styling the login UI (assignment)

Implementing the header component

Implementing the footer and page not found components

Implementing the user search dialog component

Summary

Chapter 8: Guarding Routes and Testing Authentication

Technical requirements

Guarding routes

Sending the JWT

Improving the search functionality (assignment)

Using GraphQL fragments

Local state management with Apollo Client

Using the OnPush change detection strategy

Testing the auth service and component(s)

Testing the auth service

Testing the auth guard

Testing the header component

Testing the search dialog component

Testing other components

Summary

Chapter 9: Uploading Images and Adding Posts

Technical requirements

Image uploading with Angular and Apollo

Setting up GraphQL Code Generator

Adding fragments and mutations

Generating types and services

Implementing the post service

Implementing the profile service

Implementing the base component

Implementing the profile component

Defining field policies

Creating the profile UI

Styling the profile component

Implementing the create post component

Testing

Summary

Chapter 10: Fetching Posts and Adding Comments and Likes

Technical requirements

Improving the authentication system

Adding queries and generating types and services

Fetching paginated posts

Implementing comments and likes services

Implementing a presentational post component

Displaying posts, comments, and likes

Summary

Part 3: Adding Realtime Support

Chapter 11: Implementing GraphQL Subscriptions

Technical requirements

Persisting the component state with reactive variables

Using field policies to rewrite dates

Displaying comments

Displaying new comments

Updating the cache after removing comments

Giving focus to the commenting box

Setting up Apollo Client for subscriptions

Implementing GraphQL subscriptions

Summary

Other Books You May Enjoy

Preface

Angular is one of the most popular JavaScript frameworks in modern web app development, allowing developers to not only build apps and reuse the code, but also develop apps for any deployment target. For web, mobile web, native mobile, and native desktop, GraphQL is the modern and REST alternative for querying web APIs. Using Angular, TypeScript, and GraphQL will give you a future-proof and scalable stack that you can start building apps around.

This book shows you how to build apps using cutting-edge technologies. You'll learn how to solve common web development problems with GraphQL and Apollo, such as database access, authentication, and image uploads.

The book starts by introducing you to building full stack apps with Angular and GraphQL. After that, you'll learn how to create a monorepo project with Lerna and NPM workspaces and configure a Node.js app to use GraphQL with Express and Apollo Server. You'll also understand the basics of Angular architecture and routing. Then, the book demonstrates how to build a professionally looking UI with Angular Material and use Apollo Client to interface with the server to get data from the built-in GraphQL API.

You'll learn about Apollo Client's type and field policies, and various fetching policies. In addition to this, you'll learn about local state management and reactive variables with Apollo Client and how to generate TypeScript types and even Angular Apollo services for your GraphQL schema and queries using GraphQL Code Generator to implement a scalable code base.

By the end of this book, you'll have the skills you need to be able to build your own full stack application.

Who this book is for

This Angular GraphQL book is for Angular developers who want to learn how to use GraphQL and Apollo with Angular to build full stack applications. This book does not assume prior knowledge of full stack development with Angular and GraphQL.

What this book covers

Chapter 1, App Architecture and Development Environment, teaches you about the project's structure and the tools required to develop the application. After that, you'll have your machine ready for development. Specifically, you'll install Node.js alongside npm and MySQL.

Chapter 2, Setting Up GraphQL with Node.js, Express.js, and Apollo, assists you with building your backend application to provide the API that will be consumed by your Angular application.

Chapter 3, Connecting the Database with TypeORM, teaches you how to connect a MySQL database to your application using TypeORM, as well as how to create resolvers to get and save data from the database.

Chapter 4, Implementing Authentication and Image Uploads with Apollo Server, helps you understand how to add authentication and image uploads with Apollo Server to your GraphQL API, implementing more resolvers. You'll learn about the necessary concepts for adding authentication with Node.js, Express, and Apollo Server and then how to handle image uploads.

Chapter 5, Adding Realtime Support with Apollo Server, helps you to add realtime support to your server application, which will allow you to communicate fresh data from the server to the client as soon as it becomes available. To do this, you'll use Apollo Server's GraphQL subscriptions.

Chapter 6, Angular Application Architecture and Routing, gets you started by installing the Angular CLI and creating a new project using a recent version of Angular. Following that, you'll utilize the Angular CLI to create the modules, services, and components that make up your application's UI, as well as being introduced to dependency injection.

Chapter 7, Adding User Search Functionality, specifically looks at how to integrate the frontend with the backend using Apollo Client, which is designed for sending GraphQL queries and mutations to the server to fetch and write data. Then, you'll begin implementing authentication.

Chapter 8, Guarding Routes and Testing Authentication, continues with implementing our authentication system by guarding the necessary route(s) from unauthorized access, sending the JWT with API requests, and unit testing our code.

Chapter 9, Uploading Images and Adding Posts, implements the profile component's functionality. You'll add the necessary code to fetch the user that corresponds to a profile URL and render their information on the page, including the ability to upload the user's photo and cover image as well as add a biography.

Chapter 10, Fetching Posts and Adding Comments and Likes, begins by dealing with an authentication token expiration issue, and then you'll continue working on your profile component by sending queries to receive paginated posts and comments data and mutations to add comments and likes to posts.

Chapter 11, Implementing GraphQL Subscriptions, continues with building your users' profile component before learning how to add realtime support to your application so that you can retrieve and display new data from the server without having to constantly refresh the app. You'll utilize GraphQL subscriptions with Apollo Client and Angular to do this.

To get the most out of this book

Installing Node.js and MySQL is covered in the book.

Further prerequisites are being familiar with JavaScript/TypeScript, HTML, and CSS.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Full-Stack-App-Development-with-Angular-and-GraphQL. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800202467_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Open the lerna.json file and set version to "0.0.1":"

A block of code is set as follows:

{

  "packages": [

    "packages/*"

  ],

  "version": "0.0.1"

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

import express, { Application } from 'express';

import { ApolloServer } from 'apollo-server-express';

import schema from './graphql/schema';

Any command-line input or output is written as follows:

curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "You can click on the Query your server button to access Apollo Studio, where you can send requests to your API endpoint."

Tips or Important Notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read Full-Stack Development with Angular and GraphQL, we'd love to hear your thoughts! Please select https://www.amazon.in/review/create-review/error?asin=1800202466 for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Part 1: Setting Up the Development Environment, GraphQL Server, and Database

In this part, we'll learn about our app's architecture and requirements, and we'll set up our development environment for full stack development. We'll also set up a GraphQL server with Express.js and Apollo and connect a SQL database for storing the application data using TypeORM.

This section comprises the following chapters:

Chapter 1, App Architecture and Development EnvironmentChapter 2, Setting Up GraphQL with Node.js, Express.js, and ApolloChapter 3, Connecting the Database with TypeORMChapter 4, Implementing Authentication and Image Uploads with Apollo ServerChapter 5, Adding Realtime Support with Apollo Server

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 technologiesInstalling MySQLInstalling 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:

First, the client will make a request by putting your application domain name into the address bar of the browser.The server will intercept the requests and process the HTML document containing the Angular app.The client's browser will begin downloading all of the JavaScript and CSS files required to run the Angular application.Any initial requests to the server for data, such as posts, will be sent by the Angular application and rendered in the user interface.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 commandThe operating system's official package manager, such as APT for Ubuntu, Homebrew for macOS, or Chocolatey for WindowsThe 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:

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

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.

To begin utilizing nvm, just source the following file or log out and then log back in:

source ~/.profile

Using this command, you can quickly retrieve a list of available Node.js versions that you can install:

nvm ls-remote

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.

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:

nvm-windows, which may be found at https://github.com/coreybutler/nvm-windowsnodist, which may be found at https://github.com/marcelklehr/nodist

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.

Chapter 2: Setting Up GraphQL with Node.js, Express.js, and Apollo

In the previous chapter, we prepared our development machine by installing Node.js and MySQL. We can now start building our backend application to provide the API that will be consumed by our Angular application.

For the sake of time, we'll try to build a simple social network application with a minimal set of features (a Minimum Viable Product or MVP) that will be implemented throughout the book.

First, users will be presented with a login and signup interface. In this interface, users are required to provide their email and password to log in or create an account if they are not already registered. In this case, they need to enter their full name, username, email, password, and password confirmation.

After they log in, they will be taken to an interface where they can create posts and see their feed, which will display the posts that have been added by the users of the app. They can also search for the other users by name and visit their profiles from there.

Users can see their profiles, which contain their photos and posts, and the profiles of other users.

Finally, users can add comments and likes on posts and receive notifications when someone comments or likes their posts.

After setting up the development environment and installing Node.js, we'll need to set up a Node.js server with GraphQL support to implement the backend. In this chapter, we'll explain how to install Express.js and configure it with TypeScript and GraphQL.

Next, we'll learn how to use mocking to provide a working GraphQL server with Apollo Server for testing before implementing the resolvers, which are responsible for fetching and mutating data.

We'll also learn how to configure cross-origin resource sharing (CORS) and learn how to test our GraphQL server with Apollo Studio.

In this chapter, we will cover the following topics:

Initializing our projectInstalling Express.js and adding TypeScript supportSetting up Apollo Server with Node.js Mocking our GraphQL API with Apollo ServerTesting the GraphQL server using Apollo StudioConfiguring CORS in Express.js

Technical requirements

To complete this chapter, you are required to have Node.js and npm installed on your local development machine. Please refer to Chapter 1, App Architecture and Development Environment, for instructions on how to install them if you haven't done so yet.

You also need to be familiar with the following technologies:

JavaScript/TypeScriptGit, Node.js, and ExpressGraphQL concepts such as schemas and types

If you need a refresher of GraphQL concepts, check out https://graphql.org/learn/. This is the official documentation for GraphQL schemas and it explains various features of the schema and how to use them with the schema language.

You can find the complete source code for this chapter at https://github.com/PacktPublishing/Full-Stack-App-Development-with-Angular-and-GraphQL/tree/main/Chapter02. Alternatively, you can go to https://git.io/JKZpT. Make sure that you consult the history, which contains the commits for the major steps in this chapter.

Setting up a monorepo project

We'll be taking a monorepo approach to managing our project, which simply revolves around the idea of using a single repository to manage our client and server apps (and any shared libraries) instead of working with multiple repositories. We'll be using a tool called Lerna to do this. Let's get started:

Head over to your command-line interface and run the following command to install Lerna:

npm install --global lerna

Next, create a folder for your project and initialize Lerna using the following commands:

mkdir ngsocial

cd ngsocial

lerna init

You should see an output similar to the following:

lerna notice cli v4.0.0

lerna info Initializing Git repository

lerna info Creating package.json

lerna info Creating lerna.json

lerna info Creating packages directory

lerna success Initialized Lerna files

The lerna.json file holds the configuration for Lerna, while the package.json file contains the configuration for the whole (client and server) project. The packages/ folder will contain the client and server apps, plus any libraries you would like to share between the two apps. The command will also run the git init



Tausende von E-Books und Hörbücher

Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.