• Stars
    star
    1,527
  • Rank 30,669 (Top 0.7 %)
  • Language
    JavaScript
  • Created over 7 years ago
  • Updated 7 months ago

Reviews

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

Repository Details

A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, or Blob instances), or else fetches a regular GraphQL POST or GET request (depending on the config and GraphQL operation).

Apollo upload logo

apollo-upload-client

npm version CI status

A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, Blob, or ReactNativeFile instances), or else fetches a regular GraphQL POST or GET request (depending on the config and GraphQL operation).

Installation

To install with npm, run:

npm install apollo-upload-client

Remove any uri, credentials, or headers options from the ApolloClient constructor.

Apollo Client can only have 1 terminating Apollo Link that sends the GraphQL requests; if one such as HttpLink is already setup, remove it.

Initialize the client with a terminating Apollo Link using createUploadLink.

Also ensure the GraphQL server implements the GraphQL multipart request spec and that uploads are handled correctly in resolvers.

Usage

Use FileList, File, Blob or ReactNativeFile instances anywhere within query or mutation variables to send a GraphQL multipart request.

See also the example API and client.

FileList

import { gql, useMutation } from "@apollo/client";

const MUTATION = gql`
  mutation ($files: [Upload!]!) {
    uploadFiles(files: $files) {
      success
    }
  }
`;

function UploadFiles() {
  const [mutate] = useMutation(MUTATION);

  function onChange({ target: { validity, files } }) {
    if (validity.valid) mutate({ variables: { files } });
  }

  return <input type="file" multiple required onChange={onChange} />;
}

File

import { gql, useMutation } from "@apollo/client";

const MUTATION = gql`
  mutation ($file: Upload!) {
    uploadFile(file: $file) {
      success
    }
  }
`;

function UploadFile() {
  const [mutate] = useMutation(MUTATION);

  function onChange({
    target: {
      validity,
      files: [file],
    },
  }) {
    if (validity.valid) mutate({ variables: { file } });
  }

  return <input type="file" required onChange={onChange} />;
}

Blob

import { gql, useMutation } from "@apollo/client";

const MUTATION = gql`
  mutation ($file: Upload!) {
    uploadFile(file: $file) {
      success
    }
  }
`;

function UploadFile() {
  const [mutate] = useMutation(MUTATION);

  function onChange({ target: { validity, value } }) {
    if (validity.valid) {
      const file = new Blob([value], { type: "text/plain" });

      // Optional, defaults to `blob`.
      file.name = "text.txt";

      mutate({ variables: { file } });
    }
  }

  return <input type="text" required onChange={onChange} />;
}

Requirements

Consider polyfilling:

API

class ReactNativeFile

Used to mark React Native File substitutes as it’s too risky to assume all objects with uri, type and name properties are extractable files.

Parameter Type Description
file ReactNativeFileSubstitute A React Native File substitute.

See

Examples

Ways to import.

import { ReactNativeFile } from "apollo-upload-client";
import ReactNativeFile from "apollo-upload-client/public/ReactNativeFile.js";

Ways to require.

const { ReactNativeFile } = require("apollo-upload-client");
const ReactNativeFile = require("apollo-upload-client/public/ReactNativeFile.js");

A file in React Native that can be used in query or mutation variables.

const file = new ReactNativeFile({
  uri: uriFromCameraRoll,
  name: "a.jpg",
  type: "image/jpeg",
});

function createUploadLink

Creates a terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, Blob, or ReactNativeFile instances), or else fetches a regular GraphQL POST or GET request (depending on the config and GraphQL operation).

Some of the options are similar to the createHttpLink options.

Parameter Type Description
options object Options.
options.uri string? = /graphql GraphQL endpoint URI.
options.useGETForQueries boolean? Should GET be used to fetch queries, if there are no files to upload.
options.isExtractableFile ExtractableFileMatcher? = isExtractableFile Customizes how files are matched in the GraphQL operation for extraction.
options.FormData class? FormData implementation to use, defaulting to the FormData global.
options.formDataAppendFile FormDataFileAppender? = formDataAppendFile Customizes how extracted files are appended to the FormData instance.
options.fetch Function? fetch implementation to use, defaulting to the fetch global.
options.fetchOptions FetchOptions? fetch options; overridden by upload requirements.
options.credentials string? Overrides options.fetchOptions.credentials.
options.headers object? Merges with and overrides options.fetchOptions.headers.
options.includeExtensions boolean? = false Toggles sending extensions fields to the GraphQL server.

Returns: ApolloLink — A terminating Apollo Link.

See

Examples

Ways to import.

import { createUploadLink } from "apollo-upload-client";
import createUploadLink from "apollo-upload-client/public/createUploadLink.js";

Ways to require.

const { createUploadLink } = require("apollo-upload-client");
const createUploadLink = require("apollo-upload-client/public/createUploadLink.js");

A basic Apollo Client setup.

import { ApolloClient, InMemoryCache } from "@apollo/client";
import createUploadLink from "apollo-upload-client/public/createUploadLink.js";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: createUploadLink(),
});

function formDataAppendFile

The default implementation for createUploadLink options.formDataAppendFile that uses the standard FormData.append method.

Type: FormDataFileAppender

Parameter Type Description
formData FormData FormData instance to append the specified file to.
fieldName string Field name for the file.
file * File to append.

Examples

Ways to import.

import { formDataAppendFile } from "apollo-upload-client";
import formDataAppendFile from "apollo-upload-client/public/formDataAppendFile.js";

Ways to require.

const { formDataAppendFile } = require("apollo-upload-client");
const formDataAppendFile = require("apollo-upload-client/public/formDataAppendFile.js");

function isExtractableFile

The default implementation for createUploadLink options.isExtractableFile.

Type: ExtractableFileMatcher

Parameter Type Description
value * Value to check.

Returns: boolean — Is the value an extractable file.

See

Examples

Ways to import.

import { isExtractableFile } from "apollo-upload-client";
import isExtractableFile from "apollo-upload-client/public/isExtractableFile.js";

Ways to require.

const { isExtractableFile } = require("apollo-upload-client");
const isExtractableFile = require("apollo-upload-client/public/isExtractableFile.js");

type ExtractableFileMatcher

A function that checks if a value is an extractable file.

Type: Function

Parameter Type Description
value * Value to check.

Returns: boolean — Is the value an extractable file.

See

Examples

How to check for the default exactable files, as well as a custom type of file.

import isExtractableFile from "apollo-upload-client/public/isExtractableFile.js";

const isExtractableFileEnhanced = (value) =>
  isExtractableFile(value) ||
  (typeof CustomFile !== "undefined" && value instanceof CustomFile);

type FetchOptions

GraphQL request fetch options.

Type: object

Property Type Description
headers object HTTP request headers.
credentials string? Authentication credentials mode.

See


type FormDataFileAppender

Appends a file extracted from the GraphQL operation to the FormData instance used as the fetch options.body for the GraphQL multipart request.

Parameter Type Description
formData FormData FormData instance to append the specified file to.
fieldName string Field name for the file.
file * File to append. The file type depends on what the ExtractableFileMatcher extracts.

See


type ReactNativeFileSubstitute

A React Native File substitute.

Be aware that inspecting network traffic with buggy versions of dev tools such as Flipper can interfere with the React Native FormData implementation, causing multipart requests to have network errors.

Type: object

Property Type Description
uri string Filesystem path.
name string? File name.
type string? File content type. Some environments (particularly Android) require a valid MIME type; Expo ImageResult.type is unreliable as it can be just image.

See

Examples

A camera roll file.

const fileSubstitute = {
  uri: uriFromCameraRoll,
  name: "a.jpg",
  type: "image/jpeg",
};

More Repositories

1

graphql-upload

Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
JavaScript
1,427
star
2

graphql-multipart-request-spec

A spec for GraphQL multipart form requests (file uploads).
994
star
3

graphql-react

A GraphQL client for React using modern context and hooks APIs that is lightweight (< 4 kB) but powerful; the first Relay and Apollo alternative with server side rendering.
JavaScript
718
star
4

apollo-upload-examples

A full stack demo of file uploads via GraphQL mutations using Apollo Server and apollo-upload-client.
JavaScript
427
star
5

ruck

Ruck is an open source buildless React web application framework for Deno.
JavaScript
149
star
6

Barebones

A barebones boilerplate for getting started on a bespoke front end.
JavaScript
125
star
7

Fix

A CSS normalization/reset reference.
CSS
123
star
8

next-graphql-react

A graphql-react integration for Next.js.
JavaScript
77
star
9

find-unused-exports

A Node.js CLI and equivalent JS API to find unused ECMAScript module exports in a project.
JavaScript
56
star
10

extract-files

A function to recursively extract files and their object paths within a value, replacing them with null in a deep clone without mutating the original value. FileList instances are treated as File instance arrays. Files are typically File and Blob instances.
JavaScript
54
star
11

coverage-node

A simple CLI to run Node.js and report code coverage.
JavaScript
53
star
12

graphql-api-koa

GraphQL execution and error handling middleware written from scratch for Koa.
JavaScript
52
star
13

svg-symbol-viewer

An online, no-upload drag-and-drop SVG file symbol extractor and viewer.
JavaScript
36
star
14

graphql-react-examples

Deno Ruck web app demonstrating graphql-react functionality using various GraphQL APIs.
JavaScript
36
star
15

Purty-Picker

A super lightweight visual HSL, RGB and hex color picker with a responsive, touch-friendly and customizable UI. Compatible with jQuery or Zepto.
JavaScript
36
star
16

fake-tag

A fake template literal tag to trick syntax highlighters, linters and formatters into action.
JavaScript
33
star
17

next-server-context

A Next.js App or page decorator, React context object, and React hook to access Node.js HTTP server context when rendering components.
JavaScript
31
star
18

jsdoc-md

A Node.js CLI and equivalent JS API to analyze source JSDoc and generate documentation under a given heading in a markdown file (such as readme.md).
JavaScript
26
star
19

next-router-events

A more powerful Next.js router events API.
JavaScript
26
star
20

test-director

An ultra lightweight unit test director for Node.js.
JavaScript
25
star
21

device-agnostic-ui

Device agnostic styles, components & hooks for React apps.
JavaScript
18
star
22

snapshot-assertion

Asserts a string matches a snapshot saved in a file. An environment variable can be used to save rather than assert snapshots.
JavaScript
16
star
23

Focal

Simulates a camera focus within a CSS 3D transform powered scene using CSS blur filters.
JavaScript
12
star
24

scroll-animator

Smart, lightweight functions to animate browser scroll.
JavaScript
12
star
25

graphql-http-test

A JavaScript API and CLI to test a GraphQL server for GraphQL over HTTP spec compliance.
JavaScript
12
star
26

eslint-config-env

ESLint config optimized for authoring packages that adapts to the project environment.
JavaScript
11
star
27

nova-deno

A Nova editor extension that integrates the Deno JavaScript/TypeScript runtime and tools.
JavaScript
9
star
28

webpack-watch-server

A single npm script command to start Webpack and your server in watch mode, with a unified console.
JavaScript
9
star
29

Skid

An ultra-lightweight slider utilizing Hurdler for URL hash based control.
JavaScript
8
star
30

Hurdler

Enables hash links to web page content hidden beneath layers of interaction.
JavaScript
7
star
31

audit-age

A Node.js CLI and equivalent JS API to audit the age of installed production npm packages.
JavaScript
7
star
32

ruck-website

The ruck.tech website for Ruck, an open source buildless React web application framework for Deno.
JavaScript
6
star
33

react-waterfall-render

Renders nested React components with asynchronous cached loading; useful for GraphQL clients and server side rendering.
JavaScript
6
star
34

babel-plugin-syntax-highlight

A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.
JavaScript
6
star
35

google-static-maps-styler-query

Converts a Google Maps styler array to a Google Static Maps styler URL query string.
JavaScript
5
star
36

constraint-validation-buggyfill

Prevents invalid form submission in browsers that improperly support the HTML forms spec (i.e. Safari).
JavaScript
5
star
37

babel-plugin-transform-runtime-file-extensions

A Babel plugin that adds file extensions to Babel runtime import specifiers and require paths for Node.js ESM compatibility.
JavaScript
4
star
38

eslint-plugin-optimal-modules

An ESLint plugin to enforce optimal JavaScript module design.
JavaScript
4
star
39

install-from

Reliably installs a local package into another, for testing.
JavaScript
4
star
40

babel-plugin-transform-require-extensions

A Babel plugin that transforms specified require path file extensions.
JavaScript
3
star
41

device-agnostic-ui-website

The Device Agnostic UI website.
JavaScript
3
star
42

disposable-directory

Asynchronously creates a disposable directory in the OS temporary directory that gets deleted after the callback is done or errors.
JavaScript
3
star
43

class-name-prop

A lightweight utility function to create a React className prop value for multiple class names.
JavaScript
2
star
44

replace-stack-traces

A JavaScript function to replace error stack traces and following Node.js versions at any indent in a multiline string.
JavaScript
2
star
45

revertable-globals

Sets globals in a JavaScript environment that can be easily reverted to restore the original environment; useful for testing code that relies on the presence of certain globals.
JavaScript
2
star
46

eslint-config-barebones

Barebones ESLint config, extending JavaScript Standard Style.
JavaScript
1
star