100% found this document useful (4 votes)
18 views

Download Complete Fullstack GraphQL The Complete Guide to Writing GraphQL Servers and Clients with TypeScript Gaetano Checinskil PDF for All Chapters

Clients

Uploaded by

orlanzelikcs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
18 views

Download Complete Fullstack GraphQL The Complete Guide to Writing GraphQL Servers and Clients with TypeScript Gaetano Checinskil PDF for All Chapters

Clients

Uploaded by

orlanzelikcs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Fullstack GraphQL The Complete Guide to Writing


GraphQL Servers and Clients with TypeScript
Gaetano Checinskil

https://textbookfull.com/product/fullstack-graphql-the-
complete-guide-to-writing-graphql-servers-and-clients-with-
typescript-gaetano-checinskil/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Fullstack GraphQL The Complete Guide to Writing GraphQL


Servers and Clients with TypeScript Gaetano Checinskil Roy
Derks Ed Nate Murray
https://textbookfull.com/product/fullstack-graphql-the-complete-guide-
to-writing-graphql-servers-and-clients-with-typescript-gaetano-
checinskil-roy-derks-ed-nate-murray/
textboxfull.com

FullStack React with TypeScript Learn Pro Patterns for


Hooks Testing Redux SSR and GraphQL Revision r11 Maksim
Ivanov
https://textbookfull.com/product/fullstack-react-with-typescript-
learn-pro-patterns-for-hooks-testing-redux-ssr-and-graphql-
revision-r11-maksim-ivanov/
textboxfull.com

Beginning GraphQL with React NodeJS and Apollo Greg Lim

https://textbookfull.com/product/beginning-graphql-with-react-nodejs-
and-apollo-greg-lim/

textboxfull.com

Fullstack Node js The Complete Guide to Building


Production Apps with Node js Davit Guttman

https://textbookfull.com/product/fullstack-node-js-the-complete-guide-
to-building-production-apps-with-node-js-davit-guttman/

textboxfull.com
GraphQL in Action 1st Edition Samer Buna

https://textbookfull.com/product/graphql-in-action-1st-edition-samer-
buna/

textboxfull.com

GraphQL in Action 1st Edition Samer Buna

https://textbookfull.com/product/graphql-in-action-1st-edition-samer-
buna-2/

textboxfull.com

GraphQL in Action 1st Edition Samer Buna

https://textbookfull.com/product/graphql-in-action-1st-edition-samer-
buna-3/

textboxfull.com

React Quickly: Painless web apps with React, JSX, Redux,


and GraphQL 1st Edition Azat Mardan

https://textbookfull.com/product/react-quickly-painless-web-apps-with-
react-jsx-redux-and-graphql-1st-edition-azat-mardan/

textboxfull.com

Fullstack Vue 3 The Complete Guide to Vue js 2 / Revision


13 Edition Hassan Djirdeh

https://textbookfull.com/product/fullstack-vue-3-the-complete-guide-
to-vue-js-2-revision-13-edition-hassan-djirdeh/

textboxfull.com
Fullstack GraphQL
The Complete Guide to Building GraphQL Clients and Servers

Written by Gaetano Checinski and Roy Derks


Edited by Nate Murray

© 2020 newline

All rights reserved. No portion of the book manuscript may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means beyond the number of purchased copies,
except for a single backup or archival copy. The code may be used freely in your projects,
commercial or otherwise.

The authors and publisher have taken care in preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions. No
liability is assumed for incidental or consequential damagers in connection with or arising out
of the use of the information or programs container herein.

Published by newline
Contents

What to Expect from this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
What is GraphQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Why GraphQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Usage driven and Intuitive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Self-descriptive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Other advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Join Our Discord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Hello GraphQL - GraphiQL and Github’s GraphQL Playground . . . . . . . 11


Enter GraphiQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Our First Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Named Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Multiple Queries and Renaming Result fields . . . . . . . . . . . . . . . . . . 24
Fragments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Union Types and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Mutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
GraphQL queries over HTTP - fetching with fetch and curl . . . . . . . . 37
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Hello GraphQL from Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39


A GraphQL Hello World from Node . . . . . . . . . . . . . . . . . . . . . . . 39
Making Changes with Mutations . . . . . . . . . . . . . . . . . . . . . . . . . 41
CONTENTS

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Hello GraphQL in the Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43


A GraphQL Hello World from Localhost . . . . . . . . . . . . . . . . . . . . 43
Putting the Query in the App . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Creating a Custom Hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Making Updates with Mutations . . . . . . . . . . . . . . . . . . . . . . . . . 49
Handling User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Picking a GraphQL Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54


GraphQL is just JSON over HTTP (well, usually) . . . . . . . . . . . . . . . 54
Why You Might Want a Dedicated GraphQL Client . . . . . . . . . . . . . . 55
So What Are The Options? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
graphql-request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
urql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Relay Modern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Apollo Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
What to Choose? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

The Basics of Apollo Client and React . . . . . . . . . . . . . . . . . . . . . . . . 62


Apollo Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Getting Hooked on useQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Getting hooked on useMutation . . . . . . . . . . . . . . . . . . . . . . . . . . 66
How to use Apollo Client across your app . . . . . . . . . . . . . . . . . . . . 67
ApolloClient and Testing Components . . . . . . . . . . . . . . . . . . . . . . 67
Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Building a TypeSafe GraphQL React Client App - Part 1 . . . . . . . . . . . . 72


What are we building? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Tooling and Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
TypeScript and GraphQL Types - There is a difference . . . . . . . . . . . . 75
Generating Types with graphql-codegen . . . . . . . . . . . . . . . . . . . . . 76
Generating Types for Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Generating Helper Functions for Apollo . . . . . . . . . . . . . . . . . . . . . 79
Building the Issue Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Creating the Search Component . . . . . . . . . . . . . . . . . . . . . . . . . . 83
CONTENTS

Visualizing Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Pagination with cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Tracking our cursorState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Building a TypeSafe GraphQL React Client App - Part 2 . . . . . . . . . . . . 93


What are we building? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Loading Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Mutations - Modifying Existing Data . . . . . . . . . . . . . . . . . . . . . . . 103
Mutations - Creating New Data . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Refetching Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Manually Updating the Apollo Cache . . . . . . . . . . . . . . . . . . . . . . 110
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

Your First GraphQL Server with Apollo Server . . . . . . . . . . . . . . . . . . 115


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
The Obligatory Boilerplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Mocking the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Resolvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Chaining Resolvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

Using GraphQL Servers with A Database . . . . . . . . . . . . . . . . . . . . . 137


Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Using GraphQL with a Database . . . . . . . . . . . . . . . . . . . . . . . . . 138
Queries with pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Writing Mutation Resolvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Caching and Batching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159


Optimized queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
CONTENTS

Batching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Cost computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Authentication and Authorization in GraphQL . . . . . . . . . . . . . . . . . . 178


JWT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Resolver Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Context Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Schema Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Code First GraphQL with TypeORM and TypeGraphQL . . . . . . . . . . . . 205


TypeGraphQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Implementing Pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Using Context in a Resolver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
TypeORM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Authorization with TypeGraphQL . . . . . . . . . . . . . . . . . . . . . . . . 221
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
More on TypeGraphQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

Where to Go From Here? Advanced GraphQL . . . . . . . . . . . . . . . . . . 224


What did you think? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Awesome GraphQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Say Hello . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
What to Expect from this book
Fullstack GraphQL will give you a use-case driven, hands-on introduction to the
GraphQL ecosystem. This book intends to present GraphQL to you in a problem-
oriented and pragmatic fashion - and ultimately give you the confidence to use
GraphQL in your everyday full-stack challenges.
This book shows both theoretical and conceptual aspects of GraphQL, including code
examples book using React, Node.js, and Typescript to showcase how to use GraphQL
to generate and render data.
The structure of this book is loosely inspired by the workflow of a Fullstack Engineer
and will reveal GraphQL specific concepts through the life-cycle of a real-world app.
GraphQL is an opinionated query language, with an ecosystem that will change the
way you write frontend and backend solutions.
Motivation
What is GraphQL
“A query language for your API” - The GraphQL Foundation

GraphQL is a specification to query APIs, and provides a server-side runtime to


execute those queries using a strongly typed system based on your data. Based on
the data model, GraphQL can return you the data in exactly the same format as you
request it in. It can be used language and framework agnostic, and connected to any
database or storage engine.
In 2015 the specification for GraphQL was first publicly shared with the world
by Facebook, after it was developed internally. To guarantee the continuation of
GraphQL by the community, the project was moved into the GraphQL Foundation
in 2019.

Why GraphQL?
Before we present you the problems that inspired the creation of GraphQL, let us
have a look at this famous quote:

“A language that doesn’t affect the way you think about programming, is
not worth knowing.” - Alan Perlis

GraphQL changed the way how data was transferred between applications in a fixed
format, to a new approach to dynamically transfer data between a “frontend” and
a “backend”. This allowed Facebook to tackle many problems with data fetching for
mobile applications, without having to create a new REST API for every application.
Motivation 3

As you will work through this book, we hope you won’t just add GraphQL to your
toolbox, but also develop a new way of thinking about data models, APIs and full-
stack development.
The ecosystem surrounding GraphQL gives you the tools to start building and
querying APIs, that are:
Usage Driven It encourages users to define queries that specify what data to fetch in
a granular way.
Intuitive GraphQL delivers you only the data that you request, in the exact same
format that you requested it in
Self-descriptive GraphQLs schemas are strongly typed and define a strict contract
between a query and its response. It makes GraphQL responses very predictable and
also suitable for documentation.
GraphQL embodies many lessons learned from API design that enforces several
best practices into one solution. As engineers, we’re facing the challenge of not just
building systems, but also evolving these systems to fit new requirements.

Usage driven and Intuitive


REST APIs were designed with specific use-cases in mind, making the development
of “backend” and “frontend” loosely coupled or even independent.
The design of a REST API is often directly linked to the data model of the database
that it’s reading and mutating, making it a mere abstraction layer over this database.
Motivation 4

In this example, we see a wire-frame of posts, how the underlying REST API, and a
direct comparison with GraphQL.
When the REST API was created to serve the UI of a specific frontend application, the
design of the REST API (and consequentially the data model of the database) should
always match that UI. When the UI changes, the data flow and the data model of
that database no longer match.
This can lead to a problem that often arises when you’re used to working with REST
APIs, that is called the n+1 problem. If you need to query multiple endpoints to collect
enough data to render a page, then you are already facing the n+1 problem.

The n+1 problem


This problem describes the cascade of independent requests triggered by the lack of
data in one response.
For the Developer Experience (DX) and performance reasons, it’s therefore often
desirable to fetch all of the data we need in one HTTP request to serve the UI.
However, as your application grows in size, you find that you often end up creating
a unique REST endpoint for every change in either the UI or the data model of the
database.
For example, you created an endpoint that returns user information. This information
was at first used to display a profile page but is also used to display a short overview
of a user profile. Even later, you even use this information to display the user’s avatar
somewhere else.
This raises the following questions: 1) Should the backend grow with the require-
ments of each of it’s clients? 2) Should the backend endpoints be changed as the
client’s requirements change? 3) Should the backend endpoints take configuration
parameters to suit every client?
As we think through each of those options, we will notice that they all have their
pros and cons.
Building a custom endpoint for a specific client allows you to fine-tune the backend
for maximal performance. However, this will increase the number of endpoints to
maintain.
Motivation 5

Constantly adapting one endpoint to fit new requirements won’t suffer the same
issue but it will introduce a host of other questions: - How do we migrate old clients
to the newer version? - Will we need to support both versions?
The last option combines the best of both worlds but introduces a level of indirection
and requires a custom implementation.
GraphQL implements and standardizes this approach, as you’ll discover in the first
chapters of this book.
As you see, in GraphQL there is not only an intuitive mapping between queries and
data but also it encodes the domain-specific language of your application.

Self-descriptive
REST is very minimalistic and does not enforce any types or schemas, and as a result,
validation of input and output and documentation are complementary aspects of a
REST API.
Consequently, validation and documentation is a maintenance burden. That is a
potential source of bugs if the proper discipline isn’t exhibited at all times. GraphQL
has been designed with this in mind, leading to a more robust API and less overhead
for developers.
All this is based on a GraphQL schema, a strongly typed and object-orientated
representation of the data model for the application. The schema is used to both
validate the requests and statically check the types of the operations and responses.
Being schema-driven also has an interesting side-effect, as the schema is always tied
to the operations and responses and as a result, the schema is never out of date. We
can always generate up-to-date documentation.

Other advantages
GraphQL provides many other advantages over a “traditional” approach for handling
data flows between applications, as you’ll discover in this book
Motivation 6

Prerequisites
In this book we assumed that you have at least the following skills:

• basic JavaScript knowledge (working with functions, objects, and arrays)


• a basic React understanding (at least general idea of component based approach)
• some command line skill (you know how to run a command in terminal)

Here we mostly focus on specifics of using GraphQL with Node.js, TypeScript, and
React.
The instructions we give in this book are very detailed, so if you lack some of the
listed skills - you can still follow along with the tutorials and be just fine.

Running Code Examples


Each section has an example app shipped with it. You can download code examples
from the same place where you purchased this book.
If you have any trouble finding or downloading the code examples, email us at
[email protected]¹.
In the beginning of each section you will find instructions of how to run the example
app. In order to run the examples you need a terminal app and NodeJS installed on
your machine.
Make sure you have NodeJS installed. Run node -v, it should output your current
NodeJS version:

$ node -v
v10.19.0

Anything between Node 10 through 14+ should be fine.

Here are instructions for installing NodeJS on different systems:


¹mailto:[email protected]
Motivation 7

Windows

To work with examples in this book we recommend installing Cmder² as a terminal


application.
We recommend installing node using nvm-windows³. Follow the installation instruc-
tions on the Github page.
Then run nvm to get the latest LTS version of NodeJS:

nvm install --lts

It will install the latest available LTS version.

Mac

Mac OS has a Terminal app installed by default. To launch it toggle Spotlight, search
for terminal and press Enter.
Run the following command to install nvm⁴:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/inst\


all.sh | bash

Then run nvm to get the latest LTS version of NodeJS:

nvm install --lts

This command will also set the latest LTS version as default, so you should be all set.
If you face any issues follow the troubleshooting guide for Mac OS⁵.

Linux

Most Linux distributions come with some terminal app provided by default. If you
use Linux - you probably know how to launch terminal app.
Run the following command to install nvm⁶:
²https://cmder.net/
³https://github.com/coreybutler/nvm-windows
⁴https://github.com/nvm-sh/nvm
⁵https://github.com/nvm-sh/nvm#troubleshooting-on-macos
⁶https://github.com/nvm-sh/nvm
Motivation 8

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/inst\


all.sh | bash

Then run nvm to get the latest LTS version of NodeJS:

nvm install --lts

In case of problems with installation follow the troubleshooting guide for Linux⁷.

Code Blocks And Context

Code Block Numbering

In this book, we build example applications in steps. Every time we achieve a


runnable state - we put it in a separate step folder.

1 01-first-app/
2 ├── step1
3 ├── step2
4 ├── step3
5 ... // other steps

If at some point in the chapter we achieve the state that we can run - we will tell you
how to run the version of the app from the particular step.
Some files in that folders can have numbered suffixes with *.example word in the
end:

1 src/AddNewItem0.tsx.example

If you see this - it means that we are building up to something bigger. You can jump
to the file with same name but without suffix to see a completed version of it.
Here the completed file would be src/AddNewItem.tsx.
⁷https://github.com/nvm-sh/nvm#troubleshooting-on-linux
Motivation 9

Reporting Issues
We’ve done our best to make sure that our instructions are correct and code samples
don’t contain errors. There is still a chance that you will encounter problems.
If you find a place where a concept isn’t clear or you find an inaccuracy in our
explanations or a bug in our code, you should leave a comment inline on newline.co.

If you are reading this via PDF, did you know you can read all of newline’s
books online? You can either sync your purchases from your Gumroad
account or read them via newline Pro⁸

You can also try emailing us⁹


In either case, we want to make sure that our book is precise and clear.

Getting Help
If you have any problems working through the code examples in this book, you
should try:

• leaving a comment
• joining our Discord and asking or
• send us an email.

To make it easier for us to help you include the following information:

• What revision of the book are you referring to?


• What operating system are you on? (e.g. Mac OS X 10.13.2, Windows 95)
• Which chapter and which example project are you on?
• What were you trying to accomplish?
• What have you tried already?
• What output did you expect?
• What actually happened? (Including relevant log output.)

Ideally also provide a link to a git repository where we can reproduce an issue you
are having.
⁸https://newline.co/pricing
⁹mailto:[email protected]
Motivation 10

Join Our Discord


We have a community Discord which you can join here¹⁰ and join the #graphql
channel
¹⁰https://newline.co/discord
Hello GraphQL - GraphiQL and
Github’s GraphQL Playground
In this chapter, we will be getting familiar with GraphQL by using Github’s GraphQL
explorer.
To get the most out of this chapter, we suggest you head over to The Github API
Explorer¹¹ and follow along.
Below, we’ll present code examples will guide you through GraphQL’s intuitive, rich
query language.
After this chapter you will be able to:

• Understand GraphQL schemas


• Read and write GraphQL Queries
• Explore APIs using the GraphQL Playground
• Send queries using fetch and curl

Enter GraphiQL
Once you navigate to The Github API Explorer and Sign-In you’ll be welcomed with
the online IDE that looks like this:
¹¹https://developer.github.com/v4/explorer/
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 12

This is one of the most useful developer tools GraphQL offers and is known as
GraphiQL - notice the i in the middle of that previous word. It stands for “interactive”
and it’s the GraphQL explorer.
It’s your first stop when developing and exploring any GraphQL endpoint. GraphiQL
provides an IDE experience with autocompletion, documentation and a simple query
editor.

1. it syntax checks your queries


2. you can run queries and see the results
3. you can explore the types as you work

The documentation for exploring the types might be a little intimidating at


first, but don’t worry, we’ll walk through how to make sense of it.
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 13

Our First Query


GraphQL queries look a little like JSON, here’s our first query:

query {
viewer {
login
}
}

Above you’ll see this isn’t quite JSON though, we don’t have any values! (Only keys).
The response, however is in JSON. Let’s take a look:
Here’s the response for our query above:

{
"data": {
"viewer": {
"login": "nikhedonia",
}
}
}

Notice that the shape of our request matches the shape of our response. And GraphQL
fills in the values for the keys that we requested. This shape-matching is a powerful
feature of GraphQL. But another powerful feature of GraphQL is it’s type system.
Let’s investigate what a viewer is and open the Documentation by hitting the “Docs”
button on the right-hand side.
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 14

In GraphQL every field has a type associated and can be inspected in GraphiQL by
clicking on it.
If you click on “Query” then you’ll see all available fields that you can query - and
among them you’ll find viewer: User!

In English this means “the field viewer returns a User” and the exclamation mark
means it will never return null.
The field user on the other hand is a function that takes a login of type string and
returns a User but may return null if the User doesn’t exist.
I think this is a noteworthy language choice: all field declarations are considered
optional by default.
The documentation is generated directly from the schema. The GraphQL schema
roughly looks like this:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 15

# A user is an individual's account on GitHub ...


type User {
login: String! # login is of type String. ! means it is never null
email: String # email might be null
# more fields...
}

type Query {
user(login: String!): User
viewer: User # The currently authenticated user
# more fields...
}

Above we have a minimal schema with two user-defined types: User and Query. This
is how to read it:
User has two fields: login and email, both of type String.

Because login is of type String! with an exclamation mark - it is may never be null.
However, email may be null.
Query is a type with special importance: it marks the root and describes the starting
point of any query. (Queries read data, but to write data we use what is called
mutations - more on that below).

This particular schema also exposes viewer as a field of Query, allowing


us to reach into the data it holds. The viewer parameter here returns a
User as well, but notice that there is no login parameter. That is because
viewer returns the current authenticated user. More on this below.

Let’s try to find users by their login:


Hello GraphQL - GraphiQL and Github’s GraphQL Playground 16

query {
user(login: "leebyron") {
login
name
bio
}
}

This query is asking for the user that has the login of leebyron and requests the
fields login, name and bio. It returns:

{
"data": {
"user": {
"login": "leebyron",
"name": "Lee Byron",
"bio": "I make things @robinhood, previously @facebook."
}
}
}

Lee Byron is one of the creators of GraphQL

Try putting in your own Github username and see what comes out!
If we pass a login that is not associated with any user (eg. login: "") then it will
return null:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 17

{
"data": {
"user": null
},
"errors": [
{
"type": "NOT_FOUND",
"path": [
"user"
],
"locations": [
{
"line": 7,
"column": 3
}
],
"message": "Could not resolve to a User with the login of ''."
}
]
}

Even more, the response contains also a descriptive error message with location
information and error type.
This design allows GraphQL to return a valid query response even if only partial
results - or no results - are available. We can query multiple fields and the server
will return data even if some fields can’t be “resolved”. For example, we can ask for
viewer in the same query:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 18

query {
viewer {
login
}
user(login: "") {
login
name
bio
}
}

Which will return viewer even though no user could be found:

{
"data": {
"viewer": {
"login": "nikhedonia"
},
"user": null
},
"errors": [
# ...
]
}

Named Queries
It is highly recommended to name your queries. Although the name is optional, it
is important for code generators and clients. Most clients use the name for caching
purposes.

For example, Apollo Client, a popular JavaScript client for GraphQL that
we talk more about in future chapters, uses named queries. Also, tools like
TypeScript type generation also uses named queries.
So while names are technically optional, it’s a good idea to use them.
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 19

So lets give our previous query a name:

query getUser {
user(login: "leebryon") {
login
name
bio
}
}

The name goes right after query keyword - so above, getUser is the query name.
Note that we could name our query pretty much whatever we want. Instead of
getUser, we could have named it getLeeBryon. The query name isn’t “special” insofar
as we can pick what we want.
However, the user field is “special” in that it’s defined by the schema or GraphQL
server. For example the following would not work:

query getUser {
# this wont work, example of an invalid field `getUser`
getUser(login: "leebryon") {
login
name
bio
}
}

Why does this not work? Because the inner getUser is not defined by the schema.
More specifically, remember that our schema looks like this:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 20

# A user is an individual's account on GitHub ...


type User {
login: String! # login is of type String. ! means it is never null
email: String # email might be null
# more fields...
}

type Query {
user(login: String!): User
viewer: User # The currently authenticated user
# more fields...
}

getUser is not a field on Query. The field is called user, and so that’s what we have
to use as well.

Variables
Oftentimes we want to specify a complex query and reuse it in different scenarios.
Above we searched for the login "leebryon", but we if we wanted to make a query
that could search for any login? We use GraphQL variables for this.
Variables use a special syntax. Variable names start with $ sign and must be defined
in the query arguments. Let’s have a look:

query getUser ($login: String!) {


user(login: $login) {
login
name
bio
}
}

So here we have a named query getUser that defines one input variable $login which
is a String and is mandatory (denoted by the !).
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 21

Look carefully: the $login variable is passed to the login argument of the user field.
So how do we use this variable? Well it depends on the client.
When we’re using GraphiQL we have to pass this parameter to make a valid query.
In order to pass this variable we need to expand the “Variables” pane and then enter
our variables in JSON like this:

{"login": "leebyron"}

And should look like this:

Again, try putting in your own Github username and see how the results change.
Feel free to try different fields. Check: is your email address exposed by the Github
API?

GraphQL Enforces Types and Correctness


GraphQL strictly enforces the correctness of inputs and will return an error if the
variables don’t satisfy the specification. If you provide the wrong type it will return
an error.
For example, if we try to pass the number 5 like this:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 22

{"login": 5}

then it will return:

{
"errors": [
{
"extensions": {
"value": 5,
"problems": [
{
"path": [],
"explanation": "Could not coerce value 5 to String"
}
]
},
"locations": [
{
"line": 1,
"column": 8
}
],
"message": "Variable Login of type String! was provided invalid v\
alue"
}
]
}

GraphQL doesn’t accept extra variables


For instance this will fail to execute this query:
Hello GraphQL - GraphiQL and Github’s GraphQL Playground 23

query ($Login: String!, $NotUsed: String) {


user(login: $login) {
login
name
bio
}
}

This is what the error will be:

{
"errors": [
{
"path": [
"query"
],
"extensions": {
"code": "variableNotUsed",
"variableName": "Login"
},
"locations": [
{
"line": 1,
"column": 1
}
],
"message": "Variable $Login is declared by but not used"
}
]
}

There’s actually two problems with the above query:

1. $Login is capitalized so it isn’t being used as the argument $login


2. $NotUsed is completely unused

Thankfully, GraphQL checks for that and will give us errors accordingly.
Random documents with unrelated
content Scribd suggests to you:
AH!
OH!!!!!!
Ding dong, ding dong,
Sang out a bell;
And off to church went pretty Nell,
Went pretty Nell,
Went pretty Nell,
And off to church went pretty Nell.

Ding dong, dang dong,


Called out a bell;
And off to school ran pretty Nell,
Ran pretty Nell,
Ran pretty Nell,
And off to school ran pretty Nell.

Dingling, dingling,
Laughed out a bell;
And home to tea came pretty Nell,
Came pretty Nell,
Came pretty Nell,
And home to tea came pretty Nell.

Hurry, pretty Nelly,


Patty cakes and jelly;
The tea is hot
In the big tea-pot,
Singing for you, Nelly.

Oh, dandelions, dandelions,


What have you there?—
A rosy little baby
With yellow, yellow hair.

But, dandelions, dandelions,


What can she do?—
Pucker up her little mouth
And throw a kiss to you!
Two tiny shiny negroes,
Standing there so shy,
Half hidden in the dripping clothes
Hanging up to dry.

Some one’s coming up the road,


Will she pass them by?
They pull the clothes about them close
And peep out of one eye.

“Dat’s dear Miss Nancy Dawson


What am it she’s got dar?
I t’ink it’s beau’ful oranges,
Jes’ like her golden ha’r.”

“Come here! Susannah Teabout,”


Sweet Nancy Dawson cried,
As out between the table-cloths
Susannah’s face she spied.

Susannah bashfully came forth.


Asked Nancy, “Where is Rose?”
Just then a timid giggle
Came from behind the clothes.

So Susie went and quickly brought


Rosalba into view,
And Nancy gave them each some fruit,
And bade them both “adieu”.
Do look at little Bobbie!
Dear me! he is so nobbie!
He struts about with a walking-stick,
And carries a watch that goes tick, tick!
Tick, tock!
Tick, tock!
Tick, tick, tick!
Look at little Bobbie with his walking-stick.
Amy!
Amy!
Oh, where is Amy Clare?
Little cats
On funny mats
She’s working for the fair.
There was a little boy,
And he had a little drum:
Ta ratta, ta ratta, tum-tum!
He played very loud,
And he played very fast—
Ta rumpa, ta rumpa, bum-bum!

He rattled away,
And away did he play:
Ta ratta, ta ratta, tum-tum!
Till he made all the boys
Stop their ears at his noise—
Ta rumpa, ta rumpa, bum-bum!

My dolly is a Japanese,
And will not say his A, B, C’s,
No matter how I coax and tease.
That naughty, naughty Japanese!
Go to sleep, my little baby.
See! the sun has gone to sleep;
Dream of bright white snow, my baby,
Soft and white and deep!
Dream of pretty flowers, baby,
Pink or white or blue.
Pretty little dreams, my baby,
Angels send to you!
Out from the trees in an unlooked-for place
Runs Dorothy Daw with a frightful false-face,
That grins and glares,
And thoroughly scares
Poor Minnie, who thinks it a terrible sight.
But, Minnie, don’t you mind it!
There’s a smiling face behind it—
Very naughty is Miss Dorothy to give you such a fright.
Peggie and Lollie,
Two little girls jolly;
They skipped the rope
In the summer sun!

They counted six, seven,


Eight, nine, ten, eleven,
And were tired, indeed,
When they had done.
The bubbles are gay as they float away,
And gayly they’re blown and wafted to-day.
Merrily rings the childish laughter,
Echoing straight from floor to rafter.
Even baby wond’ring stands,
Clapping both her tiny hands.
Bubbles are pretty, and float around,
But why do they burst when they touch the ground?
There were six
Little chicks,
And little girls two,
And a bush of sweet-brier grew near:
“The chicks must be fed,”
The little girls said.
“Here, chickies, here, chickies, come here!”

Then came they at last,


The chickens, so fast,
And ate all the corn they could find;
But one little chick
Was not nearly so quick
As the others who left him behind!
Down from the sill
To a sunnier spot,
Maud carefully carried
Each funny red pot.

She pulled every weed,


She sprinkled each flower,
She worked hard, indeed,
Every day for an hour;

And when she had finished,


They grew up so bright;
She clapped her fat hands,
And danced with delight.
Paul!
Paul!
Oh, where is Paul?
Let me think!
At the rink?
Paul will have a fall!
Johnny!
Johnny!
Oh, where did Johnny creep?
Upstairs,
Downstairs,
Johnny’s fast asleep.
“Come hither, ‘Brother Toodles,’
Let me deck your pretty head;”
And quickly round poor Toodles’ neck
Was hung a wreath of red.

But Toodles didn’t like the leaves;


He tried to tear them loose;
But, though he madly rushed about,
He found it was no use.
What have I behind my back?
Dear me, can’t you guess it?
Nothing but my empty hands,
If I must confess it.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like