Accelerating Server-Side Development with Fastify - Manuel Spigolon - E-Book

Accelerating Server-Side Development with Fastify E-Book

Manuel Spigolon

0,0
28,79 €

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

Mehr erfahren.
Beschreibung

This book is a complete guide to server-side app development in Fastify, written by the core contributors of this highly performant plugin-based web framework. Throughout the book, you’ll discover how it fosters code reuse, thereby improving your time to market.
Starting with an introduction to Fastify’s fundamental concepts, this guide will lead you through the development of a real-world project while providing in-depth explanations of advanced topics to prepare you to build highly maintainable and scalable backend applications. The book offers comprehensive guidance on how to design, develop, and deploy RESTful applications, including detailed instructions for building reusable components that can be leveraged across multiple projects. The book presents guidelines for creating efficient, reliable, and easy-to-maintain real-world applications. It also offers practical advice on best practices, design patterns, and how to avoid common pitfalls encountered by developers while building backend applications.
By following these guidelines and recommendations, you’ll be able to confidently design, implement, deploy, and maintain an application written in Fastify, and develop plugins and APIs to contribute to the Fastify and open source communities.

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

EPUB

Seitenzahl: 500

Veröffentlichungsjahr: 2023

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.



Table of Contents

Preface

Part 1:Fastify Basics

1

What Is Fastify?

Technical requirements

What is Fastify?

Fastify’s components

Starting your server

Lifecycle and hooks overview

The root application instance

Adding basic routes

Shorthand declaration

The handler

The Reply component

The first POST route

The Request component

Parametric routes

Adding a basic plugin instance

Understanding configuration types

Shutting down the application

Summary

2

The Plugin System and the Boot Process

Technical requirements

What is a plugin?

Creating our first plugin

The alternative plugin function signature

Exploring the options parameter

The options parameter type

The prefix option

Understanding encapsulation

Handling the context

fastify-plugin

Exploring the boot sequence

The register instance method

The after instance method

A declaration order

Handling boot and plugin errors

ERR_AVVIO_PLUGIN_TIMEOUT

Recovery from a boot error

Summary

3

Working with Routes

Technical requirements

Declaring API endpoints and managing the errors

Declaration variants

The route options

Bulk routes loading

Synchronous and asynchronous handlers

Reply is a Promise

How to reply with errors

Routing to the endpoint

The 404 handler

Router application tuning

Registering the same URLs

Reading the client’s input

The path parameters

The query string

The headers

The body

Managing the route’s scope

The route server instance

Printing the routes tree

Adding new behaviors to routes

Accessing the route’s configuration

AOP

Summary

4

Exploring Hooks

Technical requirements

What is a lifecycle?

Declaring hooks

Understanding the application lifecycle

The onRoute hook

The onRegister hook

The onReady hook

The onClose hook

Understanding the request and reply lifecycle

Handling errors inside hooks

The onRequest hook

The preParsing hook

The preValidation hook

The preHandler hook

The preSerialization hook

The onSend hook

The onResponse hook

The onError hook

The onTimeout hook

Replying from a hook

Route-level hooks

Summary

5

Exploring Validation and Serialization

Technical requirements

Understanding validation and serialization

The JSON Schema specification

Compiling a JSON Schema

Fastify’s compilers

Understanding the validation process

The validator compiler

Validation execution

Customizing the validator compiler

Flow control

Understanding the Ajv configuration

Managing the validator compiler

Configuring the default Ajv validator compiler

The validation error

Reusing JSON schemas

Building a new validator compiler

Customizing the schema validator compiler

Understanding the serialization process

The reply serializer

The serializer compiler

Managing the serializer compiler

Summary

Part 2:Build a Real-World Project

6

Project Structure and Configuration Management

Technical requirements

Designing the application structure

Setting up the repository

Understanding the application structure

Improving the application structure

Starting an optimal project

Managing project directories

Loading the configuration

Debugging your application

Sharing the application configuration across plugins

Using Fastify’s plugins

How to get a project overview

How to be reachable

Summary

7

Building a RESTful API

Technical requirements

Application outline

Defining routes

Register routes

Data source and model

Implementing the routes

createTodo

listTodo

readTodo

updateTodo

deleteTodo

changeStatus

Securing the endpoints

Loading route schemas

Schemas loader

Adding the Autohooks plugin

Implementing the Autohook plugin

Using the schemas

Don’t repeat yourself

Summary

8

Authentication, Authorization, and File Handling

Technical requirements

Authentication and authorization flow

Building the authentication layer

Authentication plugin

Authentication routes

Logout route

Adding the authorization layer

Adding the authentication layer

Updating the to-do data source

Managing uploads and downloads

Summary

9

Application Testing

Technical requirements

Writing good tests

What tests need to be written?

How to write tests?

Testing the Fastify application

Installing the test framework

Creating your node-tap cheatsheet test

How to write tests with Fastify?

How to improve the developer experience?

Dealing with complex tests

Reusing multiple requests

Mocking the data

Speeding up the test suite

Running tests in parallel

How to manage shared resources?

Where tests should run

Summary

10

Deployment and Process Monitoring for a Healthy Application

Technical requirements

Testing our Docker image with a local deployment

Hosting our DB on MongoDB Atlas

Choosing a cloud provider

Deploying to Fly.io

Setting up continuous deployment

Collecting application process data

Collecting the application process data with Prometheus

Exploring the metrics with Grafana

Summary

11

Meaningful Application Logging

Technical requirements

How to use Fastify’s logger

How Pino logs the application’s messages

Customizing logging configuration

Enhancing the default logger configuration

How to hide sensitive data

Collecting the logs

How to consolidate the logs

Consolidating logs by using Pino transports

Managing distributed logs

Summary

Part 3:Advanced Topics

12

From a Monolith to Microservices

Technical requirements

Implementing API versioning

Version constraints

URL prefixes

Filesystem-based routing prefixes

Splitting the monolith

Creating our v2 service

Building the v1 service on top of v2

Exposing our microservice via an API gateway

docker-compose to emulate a production environment

Nginx as an API gateway

@fastify/http-proxy as an API gateway

Implementing distributed logging

Summary

13

Performance Assessment and Improvement

Technical requirements

Why measure performance?

How to measure an application’s performance?

Measuring the HTTP response time

Instrumenting the Fastify application

Visualizing the tracing data

How to analyze the data

Creating a flame graph

How to check memory issues

How to identify I/O resources

How to optimize the application

Node.js internals that you need to know

The safety of parallel running

Connection management takeaways

Summary

14

Developing a GraphQL API

Technical requirements

What is GraphQL?

How does Fastify support GraphQL?

Writing the GQL schema

Defining GQL operations

How to make live a GQL schema?

Starting the GQL server

Implementing our first GQL query resolver

Implementing type object resolvers

How to improve resolver performance?

Managing GQL errors

Summary

15

Type-Safe Fastify

Technical requirements

Creating the project

Adding the tsconfig.json file

Adding the application’s entry point

Using Fastify type-providers

Generating the API documentation

Summary

Index

Other Books You May Enjoy

Preface

Fastify is a plugin-based web framework designed to be highly performant. It fosters code reuse, thereby improving your time to market.

This book is a complete guide to server-side app development in Fastify, written by the core contributors of Fastify. The book starts from the core concepts, continuing with a real-world project and even touching on more advanced topics to enable you to build highly maintainable and scalable backend applications. You’ll learn how to develop real-world RESTful applications from design to deployment, and build highly reusable components.

By the end of this book, you’ll be able to design, implement, deploy, and maintain an application written in Fastify, and you’ll also have the confidence you need to develop plugins and APIs in Fastify to contribute back to the Fastify and open source communities.

Who this book is for

This book is for mid-to expert-level backend web developers who have already used other backend web frameworks and have worked with HTTP protocol and its peculiarities. Developers looking to migrate to Fastify and learn how it can be a good fit for their next project, avoid architecture pitfalls, and build highly responsive and maintainable API servers will also find this book useful. The book assumes knowledge of JavaScript programming, Node.js, and backend development.

What this book covers

Chapter 1, What Is Fastify?, introduces Fastify, its purpose, and how it can speed up the development process. It covers the basic syntax for starting an application, adding endpoints, and configuring the server.

Chapter 2, The Plugin System and the Boot Process, explains the importance of Fastify plugins for developers, highlighting their role in achieving reusability, code sharing, and proper encapsulation between Fastify instances. The chapter focuses on the declaration and implementation of a simple plugin, gradually adding more layers to explore their interaction and dependency management.

Chapter 3, Working with Routes, covers the importance of routes in applications and how to manage them effectively with Fastify. It explains how to handle URL parameters, body, and query strings and how the router works in Fastify. The chapter also highlights the significance of Fastify’s support for async/await handlers and provides tips for avoiding pitfalls when using them.

Chapter 4, Exploring Hooks, explains how Fastify is different from other web frameworks because it uses hooks instead of middleware. Mastering these hooks is essential for building stable and production-ready server applications. The chapter provides an overview of the hooks and the life cycle of Fastify applications.

Chapter 5, Exploring Validation and Serialization, focuses on implementing secure endpoints with input validation and optimizing them with the serialization process in Fastify. The chapter emphasizes the importance of using Fastify’s built-in tools to control and adapt the default setup to suit your application’s logic. You will learn how to configure and use Fastify components to create straightforward APIs that clients can easily consume.

Chapter 6, Project Structure and Configuration Management, guides you through creating a real-world RESTful cloud-native application, putting into action what you’ve learned in previous chapters. You’ll build a solid project structure that can be reused for future projects, utilizing community packages and creating custom plugins as needed.

Chapter 7, Building a RESTful API, focuses on building a real-world Fastify application by defining routes, connecting to data sources, implementing business logic, and securing endpoints. The chapter will cover essential parts of the application, including implementing routes, connecting to data sources, securing endpoints, and applying the don’t repeat yourself (DRY) principle to make code more efficient.

Chapter 8, Authentication and File Handling, covers user authentication and file handling in our application. We’ll begin by implementing a reusable JWT authentication plugin that will handle user authentication, sessions, and authorization. We’ll also explore decorators to expose authenticated user data in route handlers. Next, we’ll develop a plugin to handle file import/export in CSV format for user to-do tasks.

Chapter 9, Application Testing, focuses on testing in Fastify. It covers the integrated testing tools and how to use them. It also explains how to run tests in parallel without requiring an HTTP server.

Chapter 10, Deployment and Process Monitoring for a Healthy Application, explores different deployment options for our Fastify API, focusing on a monolith deployment using Docker, MongoDB, and Fly.io. We will also learn about Node.js metrics and how to monitor the health of our server using Prometheus and Grafana.

Chapter 11, Meaningful Application Logging, explains how to implement effective logging in your Fastify application to keep track of what’s happening and monitor its performance. You’ll discover how to set up a logging configuration that captures all the necessary information without logging sensitive data and how to interpret and analyze logs to identify and troubleshoot issues.

Chapter 12, From a Monolith to Microservices, discusses restructuring a monolithic application into multiple modules to minimize conflicts between different teams. The chapter discusses adding new routes without increasing project complexity, splitting the monolith into microservices, and using an API gateway to route relevant calls. The chapter also covers logging, monitoring, error handling, and addressing operator questions.

Chapter 13, Performance Assessment and Improvement, focuses on optimizing the performance of your Fastify application. You will learn how to measure your code’s performance to avoid slow performance, identify bottlenecks in your code, and prevent production issues. You will be introduced to an instrumentation library to help you analyze how your server reacts to high-volume traffic. Additionally, you will learn how to interpret the measurements and take action to keep your server’s performance healthy.

Chapter 14, Developing a GraphQL API, explains how to incorporate GraphQL into your Fastify application using a specialized plugin. As GraphQL becomes increasingly popular, more and more APIs are being built with this query language. By using Fastify’s unique architecture and avoiding common mistakes, you can take full advantage of GraphQL in your application.

Chapter 15, Type-Safe Fastify, explores how Fastify’s built-in TypeScript support can help developers write more robust and maintainable applications. With compile-time type safety and better code completion, type inference, and documentation, developers can catch errors early in the development process and avoid unexpected runtime errors, leading to more stable and reliable applications. Using TypeScript with Fastify can also provide an extra layer of protection to code, making deployments safer and giving developers more confidence when developing code.

To get the most out of this book

To fully grasp the concepts discussed in this book, it is assumed that you have a basic understanding of the HTTP protocol, including the different methods and status codes. Additionally, you are expected to be familiar with running a Node.js application and can install and manage Node.js packages using npm.

Software/hardware covered in the book

Operating system requirements

Fastify 4

Windows, macOS, or Linux

Additionally, since we will be using containerization extensively throughout the book, it is recommended to have Docker installed on your machine before starting.

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/Accelerating-Server-Side-Development-with-Fastify. 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://packt.link/df1Dm

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: “The getSchemas() method returns a JSON key-value pair where the key is the schema’s $id and the value is the JSON schema itself.”

A block of code is set as follows:

{   "id": 1,   "name": "Foo",   "hobbies": [ "Soccer", "Scuba" ] }

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

"test": "tap --before=test/run-before.js test/**/**.test.js --after=test/run-after.js --no-check-coverage", "test:coverage": "tap --coverage-report=html --before=test/run-before.js test/**/**.test.js --after=test/run-after.js",

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

<absolute URI>#<local fragment>

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: “It is crucial to keep in mind that you should take care of the response status code when you implement your error handler; otherwise, it will be 500 – Server Errorby default.”

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 [email protected] 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 [email protected] 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.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781800563582

2. Submit your proof of purchase

3. That’s it! We’ll send your free PDF and other benefits to your email directly

Part 1:Fastify Basics

In this part, you will learn about the framework’s essential features and the philosophy behind it, and embrace “the Fastify way” mindset to speed up your team’s development process, leveraging the unique plugin system it offers.

In this part, we cover the following chapters:

Chapter 1, What Is Fastify?Chapter 2, The Plugin System and the Boot ProcessChapter 3, Working with RoutesChapter 4, Exploring HooksChapter 5, Exploring Validation and Serialization