Socket
Socket
Sign inDemoInstall

apollo-upload-client

Package Overview
Dependencies
1
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    apollo-upload-client

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 o


Version published
Weekly downloads
614K
increased by0.73%
Maintainers
1
Install size
53.6 kB
Created
Weekly downloads
 

Changelog

Source

15.0.0

Major

  • Updated Node.js support to ^12.20 || >= 14.13.
  • Stopped supporting Internet Explorer.
  • Changed @apollo/client from a dependency to a peer dependency, fixing #251 via #252.
  • Updated dependencies, some of which require newer Node.js versions than previously supported.
  • Replaced the the package.json exports field public subpath folder mapping (deprecated by Node.js) with a subpath pattern. Deep require paths within apollo-upload-client/public/ must now include the .js file extension.
  • Removed Babel related dependencies, config, and scripts. Published modules now contain more modern ES syntax.
  • Published modules now contain JSDoc comments, which might affect TypeScript projects.
  • The tests are now ESM in .mjs files instead of CJS in .js files.

Patch

  • Stop using hard-rejection to detect unhandled Promise rejections in tests, as Node.js v15+ does this natively.
  • Test the bundle size manually using esbuild and gzip-size, removing size-limit related dev dependencies, config, and scripts.
  • Updated GitHub Actions CI config:
    • Run tests with Node.js v12, v14, v16.
    • Updated actions/checkout to v2.
    • Updated actions/setup-node to v2.
    • Don’t specify the CI environment variable as it’s set by default.
  • More specific package main field path.
  • Simplified JSDoc related package scripts now that jsdoc-md v10 automatically generates a Prettier formatted readme.
  • Added a package test:jsdoc script that checks the readme API docs are up to date with the source JSDoc.
  • Use the .js file extension in internal require paths.
  • Clearer package and function createUploadLink description, fixing #247.
  • Fixed function createUploadLink option fetchOptions.signal bugs:
    • If the given abort controller signal is already aborted, immediately abort the fetch.
    • Use once: true when adding the abort event listener on the given abort controller signal to avoid a possible memory leak.
  • Updated a URL in the changelog entry for v14.0.0.
  • Documentation updates.
  • The file changelog.md is no longer published.

Readme

Source

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).

Setup

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} />;
}

Support

Consider polyfilling:

API

Table of contents

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.

ParameterTypeDescription
fileReactNativeFileSubstituteA 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',
});

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.

ParameterTypeDescription
optionsobjectOptions.
options.uristring? = /graphqlGraphQL endpoint URI.
options.useGETForQueriesboolean?Should GET be used to fetch queries, if there are no files to upload.
options.isExtractableFileExtractableFileMatcher? = isExtractableFileCustomizes how files are matched in the GraphQL operation for extraction.
options.FormDataclass?FormData implementation to use, defaulting to the FormData global.
options.formDataAppendFileFormDataFileAppender? = formDataAppendFileCustomizes how extracted files are appended to the FormData instance.
options.fetchFunction?fetch implementation to use, defaulting to the fetch global.
options.fetchOptionsFetchOptions?fetch options; overridden by upload requirements.
options.credentialsstring?Overrides options.fetchOptions.credentials.
options.headersobject?Merges with and overrides options.fetchOptions.headers.
options.includeExtensionsboolean? = falseToggles 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';

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

ParameterTypeDescription
formDataFormDataFormData instance to append the specified file to.
fieldNamestringField 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

ParameterTypeDescription
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

ParameterTypeDescription
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';

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

type FetchOptions

GraphQL request fetch options.

Type: object

PropertyTypeDescription
headersobjectHTTP request headers.
credentialsstring?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.

ParameterTypeDescription
formDataFormDataFormData instance to append the specified file to.
fieldNamestringField 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

PropertyTypeDescription
uristringFilesystem path.
namestring?File name.
typestring?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',
};

Keywords

FAQs

Last updated on 13 May 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc