• This repository has been archived on 27/Jan/2022
  • Stars
    star
    307
  • Rank 136,109 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Persisted Query support with Apollo Link

Automatic Persisted Queries

NOTE: This project has been merged into the @apollo/client core, which means it is now being maintained in the https://github.com/apollographql/apollo-client repo. Refer to the updated docs for usage instructions.

Problem to solve

Unlike REST APIs that use a fixed URL to load data, GraphQL provides a rich query language that can be used to express the shape of application data requirements. This is a marvellous advancement in technology, but it comes at a cost: GraphQL query strings are often much longer than REST URLS — in some cases by many kilobytes.

In practice we've seen GraphQL query sizes ranging well above 10 KB just for the query text. This is actually significant overhead when compared with a simple URL of 50-100 characters. When paired with the fact that the uplink speed from the client is typically the most bandwidth-constrained part of the chain, large queries can become bottlenecks for client performance.

Automatic Persisted Queries solves this problem by sending a generated ID instead of the query text as the request.

For more information about this solution, read this article announcing Automatic Persisted Queries.

How it works

  1. When the client makes a query, it will optimistically send a short (64-byte) cryptographic hash instead of the full query text.
  2. If the backend recognizes the hash, it will retrieve the full text of the query and execute it.
  3. If the backend doesn't recognize the hash, it will ask the client to send the hash and the query text, so it can store them mapped together for future lookups. During this request, the backend will also fulfill the data request.

This library is a client implementation for use with Apollo Client by using custom Apollo Link.

Installation

npm install apollo-link-persisted-queries --save

Usage

The persisted query link requires using the http-link. The easiest way to use them together to to concat them into a single link.

import { createPersistedQueryLink } from "apollo-link-persisted-queries";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import ApolloClient from "apollo-client";


// use this with Apollo Client
const link = createPersistedQueryLink().concat(createHttpLink({ uri: "/graphql" }));
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: link,
});

Thats it! Now your client will start sending query signatures instead of the full text resulting in improved network performance!

Options

The createPersistedQueryLink function takes an optional object with configuration. Currently the only supported configutations are a key called generateHash which receives the query and returns the hash, a function to conditionally disabled sending persisted queries on error

  • generateHash: a function that takes the query document and returns the hash. If not provided, generateHash defaults to a fast implementation of sha256 + hex digest.
  • useGETForHashedQueries: set to true to use the HTTP GET method when sending the hashed version of queries (but not for mutations). GET requests require apollo-link-http 1.4.0 or newer, and are not compatible with apollo-link-batch-http.

If you want to use GET for non-mutation queries whether or not they are hashed, pass useGETForQueries: true option to createHttpLink from apollo-link-http instead. If you want to use GET for all requests, pass fetchOptions: {method: 'GET'} to createHttpLink.

  • disable: a function which takes an ErrorResponse (see below) and returns a boolean to disable any future persited queries for that session. This defaults to disabling on PersistedQueryNotSupported or a 400 or 500 http error

ErrorResponse The argument that the optional disable function is given is an object with the following keys:

  • operation: The Operation that errored (contains query, variables, operationName, and context)
  • response: The Execution of the response (contains data and errors as well extensions if sent from the server)
  • graphQLErrors: An array of errors from the GraphQL endpoint
  • networkError: any error during the link execution or server response

Note: networkError is the value from the downlink's error callback. In most cases, graphQLErrors is the errors field of the result from the last next call. A networkError can contain additional fields, such as a GraphQL object in the case of a failing HTTP status code from apollo-link-http. In this situation, graphQLErrors is an alias for networkError.result.errors if the property exists.

Apollo Engine

Apollo Engine supports receiving and fulfulling Automatic Persisted Queries. Simply adding this link into your client app will improve your network response times when using Apollo Engine.

Protocol

Automatic Persisted Queries are made up of three parts: the query signature, error responses, and the negotiaion protocol.

Query Signature The query signature for Automatic Persisted Queries is sent along the extensions field of a request from the client. This is a transport independent way to send extra information along with the operation.

{
  operationName: 'MyQuery',
  variables: null,
  extensions: {
    persistedQuery: {
      version: 1,
      sha256Hash: hashOfQuery
    }
  }
}

When sending an Automatic Persisted Query, the client omits the query field normally present, and instead sends an extension field with a persistedQuery object as shown above. The hash must be a sha256 hash of the query string.

If the client needs to register the hash, the query signature will be the same but include the full query text like so:

{
  operationName: 'MyQuery',
  variables: null,
  query: `query MyQuery { id }`,
  extensions: {
    persistedQuery: {
      version: 1,
      sha256Hash: hashOfQuery
    }
  }
}

This should only happen once across all clients when a new query is introduced into your application.

Error Responses When the initial query signature is received by a backend, if it is unable to find the hash previously stored, it must send back the following response signature with a 200 OK status code:

{
  errors: [
    { message: 'PersistedQueryNotFound' }
  ]
}

If the backend doesn't support Automatic Persisted Queries, or does not want to support it for that particular client, it can send back the following which will tell the client to stop trying to send hashes all together:

{
  errors: [
    { message: 'PersistedQueryNotSupported' }
  ]
}

Negotiation Protocol In order to support Automatic Persisted Queries, the client and server must follow the negotiaion steps as outlined here:

Happy Path

  1. Client sends query signature with no query field
  2. Server looks up query based on hash, if found, it resolves the data
  3. Client receives data and completes request

Missing hash path

  1. Client sends query signature with no query field
  2. Server looks up query based on hash, none is found
  3. Server responds with NotFound error response
  4. Client sends both hash and query string to Server
  5. Server fulfills response and saves query string + hash for future lookup
  6. Client receives data and completes request

Build time generation

If you want to avoid hashing in the browser, you can use a build script to include the hash as part of the request. Then you pass a function to retrieve that hash when the operation is run. This works well with projects like this which uses webpack to generate the hashes at build time.

If you use the above loader, you can pass { generateHash: ({ documentId }) => documentId } to the createPersistedQueryLink call.

More Repositories

1

apollo-client

🚀  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
TypeScript
19,300
star
2

apollo-server

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
TypeScript
13,522
star
3

react-apollo

♻️ React integration for Apollo Client
JavaScript
6,887
star
4

apollo-ios

📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.
Swift
3,737
star
5

apollo-kotlin

🤖  A strongly-typed, caching GraphQL client for the JVM, Android, and Kotlin multiplatform.
Kotlin
3,382
star
6

apollo-tooling

✏️ Apollo CLI for client tooling (Mostly replaced by Rover)
TypeScript
3,042
star
7

apollo

🚀 Open source tools for GraphQL. Central repo for discussion.
JavaScript
2,626
star
8

graphql-tag

A JavaScript template literal tag that parses GraphQL queries
TypeScript
2,275
star
9

graphql-subscriptions

📰 A small module that implements GraphQL subscriptions for Node.js
TypeScript
1,567
star
10

subscriptions-transport-ws

🔃 A WebSocket client + server for GraphQL subscriptions
TypeScript
1,524
star
11

apollo-client-devtools

Apollo Client browser developer tools.
TypeScript
1,481
star
12

apollo-link

🔗 Interface for fetching and modifying control flow of GraphQL requests
TypeScript
1,438
star
13

apollo-link-state

✨ Manage your application's state with Apollo!
TypeScript
1,405
star
14

apollo-cache-persist

🎏 Simple persistence for all Apollo Cache implementations
TypeScript
1,368
star
15

fullstack-tutorial

🚀 The Apollo platform tutorial app
TypeScript
1,233
star
16

eslint-plugin-graphql

🚦 Check your GraphQL query strings against a schema.
JavaScript
1,194
star
17

router

A configurable, high-performance routing runtime for Apollo Federation 🚀
Rust
793
star
18

apollo-link-rest

Use existing REST endpoints with GraphQL
TypeScript
783
star
19

federation

🌐  Build and scale a single data graph across multiple services with Apollo's federation gateway.
TypeScript
659
star
20

apollo-fetch

🐶 Lightweight GraphQL client that supports middleware and afterware
TypeScript
576
star
21

apollo-rs

Spec compliant GraphQL Tools in Rust.
Rust
566
star
22

reason-apollo

Reason binding for Apollo Client and React Apollo
Reason
552
star
23

federation-demo

Federation 2 supersedes this demo and this example is no longer the newest. See https://www.apollographql.com/docs/federation/ for migration steps!
JavaScript
502
star
24

ac3-state-management-examples

✨ Learn Apollo Client 3's state management best practices
TypeScript
493
star
25

apollo-tracing

A GraphQL extension for performance tracing
475
star
26

apollo-client-nextjs

Apollo Client support for the Next.js App Router
TypeScript
446
star
27

persistgraphql

A build tool for GraphQL projects.
TypeScript
424
star
28

rover

The CLI for Apollo GraphOS
Rust
404
star
29

gatsby-theme-apollo

💜 Themes that we use to build Gatsby sites at Apollo
JavaScript
371
star
30

xcode-graphql

🛠 Xcode add-ons that add syntax highlighting for GraphQL query document files
Shell
276
star
31

apollo-studio-community

🎡  GraphQL developer portal featuring an IDE (Apollo Explorer), auto-documentation, metrics reporting, and more. This repo is for issues, feature requests, and preview docs. 📬
249
star
32

federation-jvm

JVM support for Apollo Federation
Java
247
star
33

supergraph-demo-fed2

🍿 Supergraph demo for Federation 2 and Apollo Router
Shell
162
star
34

principled-graphql

📈 Best practices for implementing and scaling a data graph
JavaScript
148
star
35

apollo-cache-control

A GraphQL extension for cache control
146
star
36

supergraph-demo

🍿 Compose subgraphs into a Federation v1 supergraph at build-time with static composition to power a federated graph router at runtime.
Shell
135
star
37

apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
130
star
38

spotify-showcase

A Spotify clone that showcases the Apollo GraphQL platform.
TypeScript
126
star
39

meteor-integration

🚀 meteor add apollo
JavaScript
108
star
40

frontpage-ios-app

📄 Apollo "hello world" app, for iOS
Swift
101
star
41

space-kit

👩‍🚀 Home base for Apollo's design system: https://space-kit.netlify.com
TypeScript
88
star
42

apollo-scalajs

Use Apollo GraphQL from Scala.js apps!
Scala
88
star
43

invariant-packages

Packages for working with invariant(condition, message) assertions
TypeScript
88
star
44

apollo-federation-subgraph-compatibility

A repo to test subgraph libraries compatibility with the Apollo Federation Specification
TypeScript
77
star
45

starwars-server

JavaScript
73
star
46

blog

📝 Blog website built with Wordpress and Gatsby
JavaScript
68
star
47

iOSTutorial

The tutorial application for the Apollo iOS SDK
Swift
68
star
48

odyssey-lift-off-part1

JavaScript
64
star
49

federation-jvm-spring-example

Apollo Federation JVM example implementation using Spring for GraphQL
Java
64
star
50

vscode-graphql

Apollo GraphQL VS Code extension
TypeScript
55
star
51

apollo-kotlin-tutorial

The code for the Apollo Kotlin Tutorial
Kotlin
52
star
52

docs-examples

Example code supporting the Apollo docs
TypeScript
50
star
53

docs

📚 Apollo's docs framework
MDX
42
star
54

apollo-kotlin-2-tutorial

The code for the Apollo Android Tutorial
Kotlin
38
star
55

iOSCodegenTemplate

A template for the code you need to set up to get Swift Scripting up and running.
Swift
38
star
56

datasource-rest

A caching data source for REST APIs
TypeScript
37
star
57

apollo-workbench-vscode

Apollo Workbench is a design tool that facilitates planning changes to your supergraph. It enables you to understand the overall composition and execution of any given query at design time.
TypeScript
37
star
58

apollo-utils

Monorepo of common utilities related to Apollo and GraphQL
TypeScript
35
star
59

graphql-testing-library

Testing utilities that encourage good practices for apps built with GraphQL.
TypeScript
35
star
60

federation-rs

Contains source code for Apollo Federation's Rust<--> JavaScript interop
Rust
34
star
61

react-apollo-error-template

Apollo Client issue reproduction.
JavaScript
33
star
62

embeddable-explorer

TypeScript
32
star
63

federation-migration-example

🚀Example app migrated from schema stitching to Apollo federation
JavaScript
32
star
64

odyssey-lift-off-part5-server

Odyssey Lift-off V - Server - Course Companion App
JavaScript
31
star
65

odyssey-lift-off-part5-client

Odyssey Lift-off V - Client - Course Companion App
JavaScript
28
star
66

GraphiQL-Subscriptions-Fetcher

GraphiQL's fetcher that supports GraphQL-Subscriptions with the `subscriptions-transport-ws` package
TypeScript
28
star
67

supergraph-demo-k8s-graph-ops

Archived: GitOps config repo for an Apollo GraphQL federated graph with a supergraph router and subgraph services deployed to Kubernetes.
Shell
28
star
68

apollo-ios-dev

Apollo iOS Development Repo
Swift
28
star
69

apollo-ios-pagination

Swift
26
star
70

odyssey-lift-off-part2

Odyssey Lift-off Part 2 Course Companion App
JavaScript
26
star
71

spacex

A re-creation of https://github.com/SpaceXLand/api
TypeScript
21
star
72

apollo-graphql-stream-scenes

This is used for hosting streaming scenes for OBS - for Apollo GraphQL stream
JavaScript
19
star
73

federation-next

Moved to the Router repository
Rust
19
star
74

subgraph-template-typescript-apollo-server-boilerplate

A template for a minimal setup Apollo Server 4.x using TypeScript
TypeScript
17
star
75

federation-hotchocolate

HotChocolate support for Apollo Federation
C#
16
star
76

odyssey-lift-off-part3

Odyssey Lift-off Part 3 Course Companion App
JavaScript
15
star
77

odyssey-voyage-I

JavaScript
14
star
78

typescript-repo-template

A template for TypeScript projects with pre-configured tooling
TypeScript
14
star
79

subgraph-template-typescript-apollo-server

A Typescript template for Apollo Server as a subgraph using Apollo Federation
TypeScript
13
star
80

next-apollo-example

Template for creating Apollo Client + Next.js reproductions
JavaScript
13
star
81

community

Apollo community guidelines
JavaScript
13
star
82

design-principles

Where we are defining and collaborating on our Apollo internal design principles (individually and collaboratively). This is a public repo, but intended only for use by Apollo employees.
13
star
83

odyssey-lift-off-part4

Odyssey Lift-off Part 4 Course Companion App
JavaScript
12
star
84

core-schema-js

Typescript library for processing core schemas
TypeScript
12
star
85

apollo-client-swift-playground

Swift
11
star
86

apollo-ios-codegen

Apollo iOS Code Generation
Swift
11
star
87

test-span

Rust
11
star
88

specs

Apollo Library of Technical Specifications
CSS
10
star
89

router-template

A general purpose self-hosted Apollo Router template connected to GraphOS
Dockerfile
10
star
90

apollo-midnight

A VS Code color theme based on Apollo Studio Explorer color palette.
9
star
91

serde_json_bytes

a JSON Value object with strings backed by Bytes, parsed by serde_json
Rust
8
star
92

hack-the-supergraph

JavaScript
8
star
93

subgraph-template-rust-async-graphql

A boilerplate template project for building a subgraph with async-graphql
Rust
8
star
94

router-biscuit-plugin

⚠️experimental⚠️ plugin for the router using Biscuit tokens for authorization
Rust
7
star
95

devhub

🔭 Explore all the latest resources for building apps with Apollo
JavaScript
7
star
96

client-router-e2e-tests

Apollo Client ↔️ Router E2E Test Suite
JavaScript
7
star
97

odyssey-lift-off-lab

Odyssey Lift-off Lab starter repo
JavaScript
7
star
98

graphchat

TypeScript
6
star
99

introspector-gadget

GraphQL introspection utilities
Rust
6
star
100

zen-observable-ts

Thin wrapper around zen-observable and @types/zen-observable, to support ESM exports
JavaScript
6
star