Page
1
(This page has no text content)
Page
2
GraphQL Best Practices Gain hands-on experience with schema design, security, and error handling Artur Czemiel
Page
3
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
Page
4
To my wife, Paulina, and my kids, Aleksander and Wiktor, for always being there. – Artur Czemiel
Page
5
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.
Page
6
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.
Page
7
(This page has no text content)
Page
8
Preface xiii Part 1 - Why GraphQL? 1 Unveiling the Holy Grail of Communication – GraphQL 3 Technical requirements 4 Understanding the advantage of built-in introspection 4 Working with GraphQL as a source of truth 8 Understanding the source of truth 8 Example project – book library 9 Creating self-documenting schemas 13 Custom scalars 13 Directives 14 Fields 15 Enums 16 Unions 17 Interfaces 19 Inputs 22 Understanding the GraphQL query language 23 Fragments 26 Aliases 27 Arguments 28 Variables 29 Directives 30 Response format 31 Workarounds for input unions 31 Mocking GraphQL responses 32 Summary 34 2 Applying an AI-Friendly Approach to GraphQL 35 Technical requirements 35 Understanding GraphQL AI Friendliness 36 Navigating the OpenAI playground 37 Generating documentation with AI 38 Generating real-life mocks 42 Table of Contents
Page
9
Table of Contentsviii Writing GraphQL queries with AI 44 Creating whole schemas with AI 46 Summary 47 Part 2 - Schema-First Design Patterns 3 Crafting Effective GraphQL Schemas 51 Technical requirements 52 Understanding the basics of schema design 52 Standardizing the naming of types and fields 52 Documenting types, fields, and arguments 54 Designing consumer-friendly schemas 55 Designing a schema by defining relationships before adding other fields 56 Implementing enums 58 Utilizing the @deprecated directive 59 Using pagination 60 Harnessing the power of interfaces 62 Adding well-documented custom scalars 65 Learning about directives 67 Handling authentication 68 Manipulating data 69 Summary 71 4 Building Pipes 73 Technical requirements 73 Introducing pipes 74 Logical pipes 75 Access pipes 78 Ownership pipes 83 Summary 88 Part 3 - Exploring Possible Ways to Use GraphQL 5 Transitioning from REST to GraphQL 91 Technical requirements 92 Why transition to GraphQL? 92 Transforming a REST to-do list into GraphQL 93 Passing headers 100
Page
10
Table of Contents ix Understanding response types 101 Reviewing the disadvantages of GraphQL 101 Summary 102 6 Defining GraphQL Transformers 103 Technical requirements 103 Understanding how transformers work 104 Creating your own transformer 108 Setting up the project 108 Creating the initial GraphQL schema 110 Transforming GraphQL with TypeScript 111 Running the transformed backend 121 The rise and fall of transformers 122 Summary 123 7 Understanding GraphQL Federation 125 Technical requirements 126 Why do we need federation? 126 Understanding the basic rules of federation 128 How do you merge different types? 128 What if different types have the same name? 130 How do you merge field arguments? 131 How do you merge different subgraphs that have different entities? 132 Merging schemas for federation 133 Federating schemas in a to-do list service 137 To-do list 137 Users schema 139 Supergraph 142 Running federated service 143 Meeting the need for GraphQL Federation 144 Summary 145 Part 4 - Advanced GraphQL 8 Executing Schema-First Systems 149 Technical requirements 150 Setting up our project 150 Creating the schema 151 Authentication and authorization 151
Page
11
Table of Contentsx Questions and answers 153 Connecting the schema, database, and type system 157 Handling user authorization and authentication 159 Authentication resolvers 160 The authorization mechanism 163 Mutation pipes 165 Adding question and answer types 166 Coding user mutations 166 Writing queries 169 Relation resolvers 171 Bringing the resolvers together 174 Summary 176 9 Working on the Frontend with GraphQL 179 Technical requirements 180 Setting up our project 180 Preparing our GraphQL Layer 183 Writing selectors 183 Implementing a client hook 186 Creating the system’s frontend 188 Setting up the frontend 188 Making the Home Page 193 Creating authentication pages 202 Crafting the post question page 206 Implementing the questions page 210 Summary 218 10 Keeping Data Secure 219 Technical requirements 220 Preventing denial-of-service attacks 220 Depth limiting 220 Rate limiting 223 Batching attacks 224 Preventing injection attacks 226 NoSQL GraphQL injection example 226 SQL GraphQL injection example 228 Understanding the query cost calculation 230 Summary 233
Page
12
Table of Contents xi 11 Describing Errors in GraphQL 235 Technical requirements 235 Understanding how should we throw errors in GraphQL-based servers 236 Using enums for error codes 237 Treating errors as data 240 Treating responses as unions 242 Understanding error masking 246 Summary 249 12 Documenting your Schema 251 Technical requirements 251 Writing documentation for GraphQL interfaces and types 251 Interfaces 252 Types 254 Input types 257 Crafting Markdown documentation for root queries and mutations 258 Summary 263 13 Tackling Schemas with Visualization 265 Technical requirements 267 Onboarding to the schema 268 Relations only 268 Filter by root type 270 Focusing on part of the schema 271 Traversing relations 272 Improving existing schemas using the visual environment 274 Orphan nodes 274 Too many relations 276 Spotting security fails 278 Using GraphiQL’s navigation pane 280 Summary 280
Page
13
Table of Contentsxii Part 5 - From an Idea to a Working Project 14 From an Idea to a Working Project – Backend Development with GraphQL and TypeScript 283 Technical requirements 283 Creating a system concept and schema 284 Crafting the authentication and registration part of the schema 285 Base objects 287 Salon operations 291 Client operations 294 Implementing the application’s backend 296 Setting up the project 296 Setting up ORM 298 Implementing authentication and authorization 301 Methods for salon owners 306 Methods for clients 320 Wrapping up the resolvers 325 Writing integration tests 327 Setting up the tests 327 Writing the test files 328 Summary 333 15 From an Idea to a Working Project – Frontend Integration with GraphQL and TypeScript 335 Technical requirements 336 Setting up the project 336 Preparing the GraphQL layer 340 Writing selectors 340 Implementing the client hook with authentication and authorization 344 Implementing dedicated hooks 347 Creating base atoms 360 Setting up multiple guards 361 Creating our app’s frontend 364 Routing 364 Authentication and user authorization 366 Root layout 367 Crafting the Home page 368 Registration forms 370 Salon area 376 Client area 384 Summary 390 Index 391 Other Books You May Enjoy 400
Page
14
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.
Page
15
Prefacexiv 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.
Page
16
Preface xv 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!
Page
17
Prefacexvi 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 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.
Page
18
Preface xvii 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.
Page
19
Prefacexviii 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: 1. Scan the QR code or visit the link below https://packt.link/free-ebook/978-1-83546-714-5 2. Submit your proof of purchase 3. That’s it! We’ll send your free PDF and other benefits to your email directly
Page
20
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 – GraphQL • Chapter 2, Applying an AI-Friendly Approach to GraphQL Part 1 - Why GraphQL?