• Stars
    star
    576
  • Rank 74,446 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

๐Ÿถ Lightweight GraphQL client that supports middleware and afterware

DEPRECATED

Apollo Client 2.0 no longer uses apollo-fetch but apollo-link instead. See https://www.apollographql.com/docs/react/2.0-migration.html for an example.

This module is deprecated and will not receive further updates.

apollo-fetch npm version Get on Slack

apollo-fetch is a lightweight client for GraphQL requests that supports middleware and afterware that modify requests and responses.

By default apollo-fetch uses cross-fetch, but you have the option of using a custom fetch function.

If you are interested in contributing, please read the documentation on repository structure and Contributor Guide.

Installation

npm install apollo-fetch --save

To use apollo-fetch in a web browser or mobile app, you'll need a build system capable of loading NPM packages on the client. Some common choices include Browserify, Webpack, and Meteor +1.3.

Usage

To create a fetch function capable of supporting middleware and afterware, use createApolloFetch:

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri });

To execute the fetch function, call apolloFetch directly in the following way:

apolloFetch({ query, variables, operationName }) //all apolloFetch arguments are optional
  .then(result => {
    const { data, errors, extensions } = result;
    //GraphQL errors and extensions are optional
  })
  .catch(error => {
    //respond to a network error
  });

Middleware and Afterware

Middleware and Afterware are added with use and useAfter directly to apolloFetch:

const apolloFetch = createApolloFetch();

const middleware = ({ request, options }, next) => { ... next(); };

const afterware = ({ response, options }, next) => { ... next(); };

apolloFetch.use(middleware);
apolloFetch.useAfter(afterware);

Middleware and Afterware can be chained together in any order:

const apolloFetch = createApolloFetch();
apolloFetch
  .use(middleware1)
  .use(middleware2)
  .useAfter(afterware1)
  .useAfter(afterware2)
  .use(middleware3);

Custom Fetch

For mocking and other fetching behavior, you may pass a fetch into createApolloFetch:

const customFetch = createFileFetch();
const apolloFetch = createApolloFetch({ customFetch });

Custom GraphQL to Fetch Translation

To modify how GraphQL requests are incorporated in the fetch options, you may pass a transformation function into createApolloFetch. apollo-fetch exports constructDefaultOptions to allow conditional creation of the fetch options. These transformations can be useful for servers that have different formatting for batches or other extra capabilities.

//requestOrRequests: GraphQLRequest | GraphQLRequest[]
//options: RequestInit
const constructOptions = (requestOrRequests, options) => {
  return {
    ...options,
    body: JSON.stringify(requestOrRequests),
  }
};
const apolloFetch = createApolloFetch({ constructOptions });

//simplified usage inside apolloFetch
fetch(uri, constructOptions(requestOrRequests, options)); //requestOrRequests and options are the results from middleware

Batched Requests

Batched requests are also supported by the fetch function returned by createApolloFetch, please refer the batched request guide for a complete description.

Examples

Simple GraphQL Query

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';

const query = `
  query CurrentUser {
    currentUser {
      login,
    }
  }
`
const apolloFetch = createApolloFetch({ uri });

apolloFetch({ query }).then(...).catch(...);

Simple GraphQL Mutation with Variables

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';

const query = `
  mutation SubmitRepo ($repoFullName: String!) {
    submitRepository (repoFullName: $repoFullName) {
      id,
      score,
    }
  }
`;

const variables = {
  repoFullName: 'apollographql/apollo-fetch',
};

const apolloFetch = createApolloFetch({ uri });

apolloFetch({ query, variables }).then(...).catch(...);

Middleware

A GraphQL mutation with authentication middleware. Middleware has access to the GraphQL query and the options passed to fetch.

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';

const apolloFetch = createApolloFetch({ uri });

apolloFetch.use(({ request, options }, next) => {
  if (!options.headers) {
    options.headers = {};  // Create the headers object if needed.
  }
  options.headers['authorization'] = 'created token';

  next();
});

apolloFetch(...).then(...).catch(...);

Afterware

Afterware to check the response status and logout on a 401. The afterware has access to the raw reponse always and parsed response when the data is proper JSON.

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';

const apolloFetch = createApolloFetch({ uri });

apolloFetch.useAfter(({ response }, next) => {
  if (response.status === 401) {
    logout();
  }
  next();
});

apolloFetch(...).then(...).catch(...);

Mocking a Fetch Call

This example uses a custom fetch to mock an unauthorized(401) request with a non-standard response body. apollo-fetch replaces the call to fetch with customFetch, which both follow the standard Fetch API.

const customFetch = () => new Promise((resolve, reject) => {
  const init = {
    status: 401,
    statusText: 'Unauthorized',
  };
  const body = JSON.stringify({
    data: {
      user: null,
    }
  });
  resolve(new Response(body, init));
}

const apolloFetch = createApolloFetch({ customFetch });

Error Handling

All responses are passed to the afterware regardless of the http status code. Network errors, FetchError, are thrown after the afterware is run and if no parsed response is received.

This example shows an afterware that can receive a 401 with an unparsable response and return a valid FetchResult. Currently all other status codes that have an uparsable response would throw an error. This means if a server returns a parsable GraphQL result on a 403 for example, the result would be passed to then without error. Errors in Middleware and Afterware are propagated without modification.

import { createApolloFetch } from 'apollo-fetch';

const uri = 'http://api.githunt.com/graphql';

const apolloFetch = createApolloFetch({ uri });

apolloFetch.useAfter(({ response }, next) => {
  //response.raw will be a non-null string
  //response.parsed may be a FetchResult or undefined

  if (response.status === 401 && !response.parsed) {
    //set parsed response to valid FetchResult
    response.parsed = {
      data: { user: null },
    };
  }

  next();
});

//Here catch() receives all responses with unparsable data
apolloFetch(...).then(...).catch(...);

Apollo Integration

apollo-fetch is the first part of Apollo Client's future network stack. If you would like to try it out today, you may replace the network interface with the following:

import ApolloClient from 'apollo-client';
import { createApolloFetch } from 'apollo-fetch';
import { print } from 'graphql/language/printer';

const uri = 'http://api.githunt.com/graphql';

const apolloFetch = createApolloFetch({ uri });

const networkInterface = {
  query: (req) => apolloFetch({...req, query: print(req.query)}),
};

const client = new ApolloClient({
  networkInterface,
});

API

createApolloFetch is a factory for ApolloFetch, a fetch function with middleware and afterware capabilities. Response and RequestInit follow the MDN standard fetch API.

createApolloFetch(options: FetchOptions): ApolloFetch

FetchOptions {
  uri?: string;
  customFetch?: (request: RequestInfo, init: RequestInit) => Promise<Response>;
  constructOptions?: (requestOrRequests: GraphQLRequest | GraphQLRequest[], options: RequestInit) => RequestInit;
}
/*
 * defaults:
 * uri = '/graphql'
 * customFetch = fetch from cross-fetch
 * constructOptions = constructDefaultOptions(exported from apollo-fetch)
 */

ApolloFetch, a fetch function with middleware, afterware, and batched request capabilities. For information on batch usage, see the batched request documentation.

ApolloFetch {
  (operation: GraphQLRequest): Promise<FetchResult>;
  use: (middlewares: MiddlewareInterface) => ApolloFetch;
  useAfter: (afterwares: AfterwareInterface) => ApolloFetch;

  //Batched requests are described in the docs/batch.md
  (operation: GraphQLRequest[]): Promise<FetchResult[]>;
  batchUse: (middlewares: BatchMiddlewareInterface) => ApolloFetch;
  batchUseAfter: (afterwares: BatchAfterwareInterface) => ApolloFetch;
}

GraphQLRequest is the argument to an ApolloFetch call. query is optional to support persistent queries based on only an operationName.

GraphQLRequest {
  query?: string;
  variables?: object;
  operationName?: string;
}

FetchResult is the return value of an ApolloFetch call

FetchResult {
  data: any;
  errors?: any;
  extensions?: any;
}

Middleware used by ApolloFetch

MiddlewareInterface: (request: RequestAndOptions, next: Function) => void

RequestAndOptions {
  request: GraphQLRequest;
  options: RequestInit;
}

Afterware used by ApolloFetch

AfterwareInterface: (response: ResponseAndOptions, next: Function) => void

ResponseAndOptions {
  response: ParsedResponse;
  options: RequestInit;
}

ParsedResponse adds raw (the body from the .text() call) to the fetch result, and parsed (the parsed JSON from raw) to the fetch's standard Response.

ParsedResponse extends Response {
  raw: string;
  parsed?: any;
}

A FetchError is returned from a failed call to ApolloFetch is standard Error that contains the response and a possible parse error. The parseError is generated when the raw response is not valid JSON (when JSON.parse() throws) and the Afterware does not add an object to the response's parsed property. Errors in Middleware and Afterware are propagated without modification.

FetchError extends Error {
  response: ParsedResponse;
  parseError?: Error;
}

More Repositories

1

apollo-client

๐Ÿš€ ย A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
TypeScript
18,905
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,471
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,363
star
15

fullstack-tutorial

๐Ÿš€ The Apollo platform tutorial app
TypeScript
1,241
star
16

eslint-plugin-graphql

๐Ÿšฆ Check your GraphQL query strings against a schema.
JavaScript
1,194
star
17

apollo-link-rest

Use existing REST endpoints with GraphQL
TypeScript
783
star
18

router

A configurable, high-performance routing runtime for Apollo Federation ๐Ÿš€
Rust
737
star
19

federation

๐ŸŒ ย Build and scale a single data graph across multiple services with Apollo's federation gateway.
TypeScript
638
star
20

apollo-rs

Spec compliant GraphQL Tools in Rust.
Rust
556
star
21

reason-apollo

Reason binding for Apollo Client and React Apollo
Reason
555
star
22

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
504
star
23

ac3-state-management-examples

โœจ Learn Apollo Client 3's state management best practices
TypeScript
491
star
24

apollo-tracing

A GraphQL extension for performance tracing
475
star
25

persistgraphql

A build tool for GraphQL projects.
TypeScript
424
star
26

rover

โœจ๐Ÿค– ๐Ÿถ The CLI for Apollo GraphOS
Rust
389
star
27

gatsby-theme-apollo

๐Ÿ’œ Themes that we use to build Gatsby sites at Apollo
JavaScript
371
star
28

apollo-client-nextjs

Apollo Client support for the Next.js App Router
TypeScript
337
star
29

apollo-link-persisted-queries

Persisted Query support with Apollo Link
TypeScript
307
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. ๐Ÿ“ฌ
246
star
32

federation-jvm

JVM support for Apollo Federation
Java
233
star
33

supergraph-demo-fed2

๐Ÿฟ Supergraph demo for Federation 2 and Apollo Router
Shell
155
star
34

apollo-cache-control

A GraphQL extension for cache control
146
star
35

principled-graphql

๐Ÿ“ˆ Best practices for implementing and scaling a data graph
JavaScript
145
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
131
star
37

apollo-feature-requests

๐Ÿง‘โ€๐Ÿš€ Apollo Client Feature Requests | (no ๐Ÿ› please).
128
star
38

spotify-showcase

A Spotify clone that showcases the Apollo GraphQL platform.
TypeScript
109
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
89
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
86
star
44

apollo-federation-subgraph-compatibility

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

starwars-server

JavaScript
72
star
46

blog

๐Ÿ“ Blog website built with Wordpress and Gatsby
JavaScript
68
star
47

iOSTutorial

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

odyssey-lift-off-part1

JavaScript
61
star
49

federation-jvm-spring-example

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

vscode-graphql

Apollo GraphQL VS Code extension
TypeScript
49
star
51

apollo-kotlin-tutorial

The code for the Apollo Kotlin Tutorial
Kotlin
49
star
52

docs-examples

Example code supporting the Apollo docs
TypeScript
46
star
53

apollo-kotlin-2-tutorial

The code for the Apollo Android Tutorial
Kotlin
38
star
54

iOSCodegenTemplate

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

docs

๐Ÿ“š Apollo's docs framework
MDX
36
star
56

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
36
star
57

react-apollo-error-template

Apollo Client issue reproduction.
JavaScript
33
star
58

apollo-utils

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

federation-rs

Contains source code for Apollo Federation's Rust<--> JavaScript interop
Rust
32
star
60

federation-migration-example

๐Ÿš€Example app migrated from schema stitching to Apollo federation
JavaScript
32
star
61

odyssey-lift-off-part5-server

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

embeddable-explorer

TypeScript
31
star
63

odyssey-lift-off-part5-client

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

datasource-rest

A caching data source for REST APIs
TypeScript
28
star
65

GraphiQL-Subscriptions-Fetcher

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

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
27
star
67

odyssey-lift-off-part2

Odyssey Lift-off Part 2 Course Companion App
JavaScript
25
star
68

apollo-graphql-stream-scenes

This is used for hosting streaming scenes for OBS - for Apollo GraphQL stream
JavaScript
20
star
69

spacex

A re-creation of https://github.com/SpaceXLand/api
TypeScript
18
star
70

odyssey-voyage-I

JavaScript
14
star
71

federation-hotchocolate

HotChocolate support for Apollo Federation
C#
14
star
72

typescript-repo-template

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

odyssey-lift-off-part3

Odyssey Lift-off Part 3 Course Companion App
JavaScript
14
star
74

federation-next

Home of the rust rewrite of federation core (composition & query planning)
Rust
14
star
75

apollo-ios-dev

Apollo iOS Development Repo
Swift
14
star
76

odyssey-lift-off-part4

Odyssey Lift-off Part 4 Course Companion App
JavaScript
13
star
77

subgraph-template-typescript-apollo-server

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

community

Apollo community guidelines
JavaScript
13
star
79

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
80

core-schema-js

Typescript library for processing core schemas
TypeScript
12
star
81

apollo-client-swift-playground

Swift
11
star
82

test-span

Rust
11
star
83

subgraph-template-typescript-apollo-server-boilerplate

A template for a minimal setup Apollo Server 4.x using TypeScript
TypeScript
11
star
84

apollo-ios-pagination

Swift
10
star
85

specs

Apollo Library of Technical Specifications
CSS
10
star
86

apollo-midnight

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

devhub

๐Ÿ”ญ Explore all the latest resources for building apps with Apollo
JavaScript
8
star
88

serde_json_bytes

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

hack-the-supergraph

JavaScript
8
star
90

next-apollo-example

Template for creating Apollo Client + Next.js reproductions
JavaScript
8
star
91

router-biscuit-plugin

โš ๏ธexperimentalโš ๏ธ plugin for the router using Biscuit tokens for authorization
Rust
7
star
92

apollo-ios-codegen

Apollo iOS Code Generation
Swift
7
star
93

odyssey-lift-off-lab

Odyssey Lift-off Lab starter repo
JavaScript
7
star
94

zen-observable-ts

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

router-template

A general purpose self-hosted Apollo Router template connected to GraphOS
Dockerfile
7
star
96

introspector-gadget

GraphQL introspection utilities
Rust
6
star
97

client-router-e2e-tests

Apollo Client โ†”๏ธ Router E2E Test Suite
JavaScript
6
star
98

subgraph-template-rust-async-graphql

A boilerplate template project for building a subgraph with async-graphql
Rust
6
star
99

odyssey-voyage-II-server

The course companion app to Odyssey's Federation series.
JavaScript
5
star
100

apollo-server-starter

A starter/demonstration repo of Apollo Server
JavaScript
5
star