GraphQL Best Practices - Artur Czemiel - E-Book

GraphQL Best Practices E-Book

Artur Czemiel

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

In the ever-evolving landscape of web development, GraphQL has emerged as a powerful query language that addresses the limitations of traditional REST APIs. This guide delves deep into GraphQL, starting with its foundational principles and swiftly advancing to complex topics that will equip you with the skills you need to understand this technology.
As you progress, you’ll cover advanced concepts such as schema design, security enhancements, and error handling. You'll also explore essential topics such as federation and the transition from REST to GraphQL, gaining a comprehensive understanding of these critical areas. The book helps you learn through practical examples in TypeScript, guiding you through building scalable and secure GraphQL backends. Additionally, you’ll get up to speed with the intricacies of frontend integration.
By the end of this book, you’ll have the skills you need to implement real-world GraphQL solutions, creating efficient and robust applications that meet modern web development demands.

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

EPUB
MOBI

Seitenzahl: 384

Veröffentlichungsjahr: 2024

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.



GraphQL Best Practices

Gain hands-on experience with schema design, security, and error handling

Artur Czemiel

GraphQL Best Practices

Copyright © 2024 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: Kaustubh Manglurkar

Publishing Product Manager: Urvi Sambhav Shah

Book Project Manager: Sonam Pandey

Senior Editor: Hayden Edwards

Technical Editor: Simran Ali

Copy Editor: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Alishon Mendonca

DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

First published: October 2024

Production reference: 1120924

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN: 978-1-83546-714-5

www.packtpub.com

To my wife, Paulina, and my kids, Aleksander and Wiktor, for always being there.

– Artur Czemiel

Contributors

About the author

Artur Czemiel is a co-founder of the GraphQL Editor and owner of the Aexol agency, with over 15 years of experience in GraphQL, TypeScript, and full stack development. He is also the creator of the GraphQL client generator, GraphQL Zeus (available on GitHub), and the GraphQL backend engine, Axolotl.

Before this, Artur was a visual effects (VFX) specialist, writing Python scripts for movie effects, and patented an algorithm for weighing small objects with a smartphone.

Artur holds a computer science engineering degree, with his thesis on the measurement of temperature using a smartphone and sound waves.

I want to thank the people who have been close to me and supported me, especially my wife, Paulina; the co-founders of my company, Tomek and Kamil; my friends, Wojtek and Maciek; my friend Sarin, who invited me to the conference to talk about GraphQL; my parents, Leszek and Jola (who is a writer, so she helped me a little); my mother-in-law, Ewa, who helps me raise my kids; and my siblings, Magda, Kuba, Mikołaj, and Maks, who always support me.

I also want to thank the Packt team for being super professional.

About the reviewers

Fadi William Ghali Abdelmessih is a seasoned full stack software engineer with extensive experience in both frontend and backend development, specializing in React, Spring Boot, and Node.js. His expertise also extends to mobile application development for both iOS and Android, spanning the banking and entertainment industries, where he has developed robust applications tailored to these sectors. At Microsoft, he served as a partner technical consultant, focusing on cloud application development.

Fadi holds a master’s degree in computer fundamentals and engineering from Polytech Nice Sophia, France, and a BSc in computer engineering from the French University in Egypt.

Martyn Robotham is an experienced web developer with nearly 10 years of experience developing full stack and frontend web applications. He has also been a mentor to others, guiding them and helping them grow in their careers. He has worked with a variety of technologies in .NET and frontend web development, working across a diverse set of technologies and industries.

Ryan Dsouza is a full stack cloud-native engineer, architecting apps using optimal practices from development to deployment. He has worked with Node, React, Python, Docker, and various AWS services such as Lambda, ECS, SQS, SNS, and AppSync. He also has expertise in CI/CD solutions and advocates for infrastructure as code and serverless solutions.

Table of Contents

Preface

Part 1 - Why GraphQL?

1

Unveiling the Holy Grail of Communication – GraphQL

Technical requirements

Understanding the advantage of built-in introspection

Working with GraphQL as a source of truth

Understanding the source of truth

Example project – book library

Creating self-documenting schemas

Custom scalars

Directives

Fields

Enums

Unions

Interfaces

Inputs

Understanding the GraphQL query language

Fragments

Aliases

Arguments

Variables

Directives

Response format

Workarounds for input unions

Mocking GraphQL responses

Summary

2

Applying an AI-Friendly Approach to GraphQL

Technical requirements

Understanding GraphQL AI Friendliness

Navigating the OpenAI playground

Generating documentation with AI

Generating real-life mocks

Writing GraphQL queries with AI

Creating whole schemas with AI

Summary

Part 2 - Schema-First Design Patterns

3

Crafting Effective GraphQL Schemas

Technical requirements

Understanding the basics of schema design

Standardizing the naming of types and fields

Documenting types, fields, and arguments

Designing consumer-friendly schemas

Designing a schema by defining relationships before adding other fields

Implementing enums

Utilizing the @deprecated directive

Using pagination

Harnessing the power of interfaces

Adding well-documented custom scalars

Learning about directives

Handling authentication

Manipulating data

Summary

4

Building Pipes

Technical requirements

Introducing pipes

Logical pipes

Access pipes

Ownership pipes

Summary

Part 3 - Exploring Possible Ways to Use GraphQL

5

Transitioning from REST to GraphQL

Technical requirements

Why transition to GraphQL?

Transforming a REST to-do list into GraphQL

Passing headers

Understanding response types

Reviewing the disadvantages of GraphQL

Summary

6

Defining GraphQL Transformers

Technical requirements

Understanding how transformers work

Creating your own transformer

Setting up the project

Creating the initial GraphQL schema

Transforming GraphQL with TypeScript

Running the transformed backend

The rise and fall of transformers

Summary

7

Understanding GraphQL Federation

Technical requirements

Why do we need federation?

Understanding the basic rules of federation

How do you merge different types?

What if different types have the same name?

How do you merge field arguments?

How do you merge different subgraphs that have different entities?

Merging schemas for federation

Federating schemas in a to-do list service

To-do list

Users schema

Supergraph

Running federated service

Meeting the need for GraphQL Federation

Summary

Part 4 - Advanced GraphQL

8

Executing Schema-First Systems

Technical requirements

Setting up our project

Creating the schema

Authentication and authorization

Questions and answers

Connecting the schema, database, and type system

Handling user authorization and authentication

Authentication resolvers

The authorization mechanism

Mutation pipes

Adding question and answer types

Coding user mutations

Writing queries

Relation resolvers

Bringing the resolvers together

Summary

9

Working on the Frontend with GraphQL

Technical requirements

Setting up our project

Preparing our GraphQL Layer

Writing selectors

Implementing a client hook

Creating the system’s frontend

Setting up the frontend

Making the Home Page

Creating authentication pages

Crafting the post question page

Implementing the questions page

Summary

10

Keeping Data Secure

Technical requirements

Preventing denial-of-service attacks

Depth limiting

Rate limiting

Batching attacks

Preventing injection attacks

NoSQL GraphQL injection example

SQL GraphQL injection example

Understanding the query cost calculation

Summary

11

Describing Errors in GraphQL

Technical requirements

Understanding how should we throw errors in GraphQL-based servers

Using enums for error codes

Treating errors as data

Treating responses as unions

Understanding error masking

Summary

12

Documenting your Schema

Technical requirements

Writing documentation for GraphQL interfaces and types

Interfaces

Types

Input types

Crafting Markdown documentation for root queries and mutations

Summary

13

Tackling Schemas with Visualization

Technical requirements

Onboarding to the schema

Relations only

Filter by root type

Focusing on part of the schema

Traversing relations

Improving existing schemas using the visual environment

Orphan nodes

Too many relations

Spotting security fails

Using GraphiQL’s navigation pane

Summary

Part 5 - From an Idea to a Working Project

14

From an Idea to a Working Project – Backend Development with GraphQL and TypeScript

Technical requirements

Creating a system concept and schema

Crafting the authentication and registration part of the schema

Base objects

Salon operations

Client operations

Implementing the application’s backend

Setting up the project

Setting up ORM

Implementing authentication and authorization

Methods for salon owners

Methods for clients

Wrapping up the resolvers

Writing integration tests

Setting up the tests

Writing the test files

Summary

15

From an Idea to a Working Project – Frontend Integration with GraphQL and TypeScript

Technical requirements

Setting up the project

Preparing the GraphQL layer

Writing selectors

Implementing the client hook with authentication and authorization

Implementing dedicated hooks

Creating base atoms

Setting up multiple guards

Creating our app’s frontend

Routing

Authentication and user authorization

Root layout

Crafting the Home page

Registration forms

Salon area

Client area

Summary

Index

Other Books You May Enjoy

Preface

Specifying the structure of web backends has always been an integral part of most software projects. However, it can often be a challenge, due to the numerous technologies available for specification. As a result, the software industry is constantly searching for the ideal solution.

I have been interested in specifying software products from the very beginning of my career when I was a VFX developer. I developed plugins for a popular 3D software, and I frequently received requests to create small web-based apps that would enhance a company’s workflow. I would ask myself the question, “Wouldn’t it be sufficient to just specify the data structure that holds business data and generate everything else out of it?”

In this regard, GraphQL emerges as a highly promising candidate. It offers a compelling alternative that addresses the complexities faced by developers, providing a clear and concise approach to backend specification – not only because it is a good language to specify structures and systems, but also because it’s already widely adopted and developers have already accepted it.

The goal of this book is for you to learn GraphQL and full stack development based on the GraphQL schema. Within this book, you will learn how to create transformer libraries, use AI to generate GraphQL schema and docs, build a frontend communication layer for GraphQL, and build great schema-first backends.

Who this book is for

This book is for developers interested in advancing their knowledge of GraphQL, from beginners curious about the basics to experienced developers looking to refine their schema design and security strategies. It’s particularly ideal for backend developers, full stack professionals, and frontend developers who wish to understand GraphQL from the ground up and apply advanced techniques in real-world scenarios. Additionally, this book is a must-read for anyone looking to make their applications more efficient and robust using GraphQL.

What this book covers

In Chapter 1, Unveiling the Holy Grail of Communication – GraphQL, you will learn what GraphQL is and how it changes the way development teams communicate.

In Chapter 2, Applying an AI-Friendly Approach to GraphQL, you will learn how to generate parts of GraphQL using AI.

In Chapter 3, Crafting Effective GraphQL Schemas, we will examine all the features of GraphQL and learn how to create consumer-friendly schemas.

In Chapter 4, Building Pipes, you will learn how to use access-based resolvers in GraphQL.

In Chapter 5, Transitioning from REST to GraphQL, you will learn how to move from REST to GraphQL and write GraphQL proxies for existing REST backends.

In Chapter 6, Defining GraphQL Transformers, you will learn what a transformer is and how to write one of your own.

In Chapter 7, Understanding GraphQL Federation, we will try to understand what federation is and why it was created.

In Chapter 8, Executing Schema-First Systems, we will create a GraphQL-based backend for a Questions and Answers project.

In Chapter 9, Working on the Frontend with GraphQL, we will create a frontend for our Questions and Answers project with a GraphQL layer.

In Chapter 10, Keeping Data Secure, you will learn how to design GraphQL schema with security in mind and avoid exposing sensitive data.

In Chapter 11, Describing Errors in GraphQL, you will learn how GraphQL can help shape the data of returned errors.

In Chapter 12, Documenting your Schema, you will learn how to write good documentation for your GraphQL-based systems.

In Chapter 13, Tackling Schemas with Visualization, you will learn how to read visual graphs and filter out specific information.

In Chapter 14, From an Idea to a Working Project – Backend Development with GraphQL and TypeScript, we will create a complicated backend for a booking system that a small business such as a hairdresser could use.

In Chapter 15, From an Idea to a Working Project – Frontend Integration with GraphQL and TypeScript, we will continue our booking system project by creating a frontend for the system.

To get the most out of this book

To get the most out of this book, you just need a computer that runs Node.js and TypeScript with either Windows, macOS, or Linux. You have to be a software developer to write full stack code, but if you’re not, the theoretical part of the book will still be useful for you to understand how data is shaped using GraphQL.

Software/hardware covered in the book

Operating system requirements

GraphQL Editor

Windows, macOS, or Linux

TypeScript 5.x

Axolotl

GraphQL Yoga

GraphQL Zeus

GraphQL Demeter

React 18.x

OpenAI

Shadcn UI

All the software used throughout the book has open source versions.

After reading this book, deploy at least one full stack project to cement your knowledge.

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/GraphQL-Best-Practices. 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!

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: “Within the __schema field, we retrieve the queryType, mutationType, and subscriptionType fields.”

A block of code is set as follows:

type Todo {   id: ID!   title: String!   completed: Boolean! }

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “To do this, click the Filter by root type button at the top menu of GraphQL Editor.”

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.

Share Your Thoughts

Once you’ve read GraphQL Best Practices, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page 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.

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/978-1-83546-714-5

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1 - Why GraphQL?

In the first part of the book, you will learn what GraphQL is and why it is a game-changer for development team communications. You will also learn how we can utilize AI to help us build consistent schemas and generate documentation.

This part contains the following chapters:

Chapter 1, Unveiling the Holy Grail of Communication – GraphQLChapter 2, Applying an AI-Friendly Approach to GraphQL