or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdupload-http-link.mdutility-functions.md
tile.json

upload-http-link.mddocs/

Upload HTTP Link

The UploadHttpLink class is a terminating Apollo Link that handles GraphQL file uploads by automatically detecting files in variables and creating multipart requests, or falling back to regular GraphQL requests when no files are present.

Capabilities

UploadHttpLink Class

Creates a terminating Apollo Link for handling file uploads and regular GraphQL requests.

/**
 * A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart 
 * request if the GraphQL variables contain files, or else fetches a regular 
 * GraphQL POST or GET request.
 */
export default class UploadHttpLink extends ApolloLink {
  constructor(options?: UploadHttpLinkOptions);
}

interface UploadHttpLinkOptions {
  /** GraphQL endpoint URI. Defaults to "/graphql" */
  uri?: string;
  /** Should GET be used to fetch queries, if there are no files to upload */
  useGETForQueries?: boolean;
  /** Matches extractable files in the GraphQL operation. Defaults to isExtractableFile */
  isExtractableFile?: ExtractableFileMatcher;
  /** FormData class. Defaults to the FormData global */
  FormData?: typeof FormData;
  /** Customizes how extracted files are appended to the FormData instance. Defaults to formDataAppendFile */
  formDataAppendFile?: FormDataFileAppender;
  /** Prints the GraphQL query or mutation AST to a string for transport. Defaults to defaultPrinter */
  print?: BaseHttpLinkPrinter;
  /** fetch implementation. Defaults to the fetch global */
  fetch?: typeof fetch;
  /** fetch options; overridden by upload requirements */
  fetchOptions?: RequestInit;
  /** Overrides credentials in fetchOptions */
  credentials?: string;
  /** Merges with and overrides headers in fetchOptions */
  headers?: { [headerName: string]: string };
  /** Toggles sending extensions fields to the GraphQL server. Defaults to false */
  includeExtensions?: boolean;
  /** Toggles including unused GraphQL variables in the request. Defaults to false */
  includeUnusedVariables?: boolean;
}

Usage Examples:

import UploadHttpLink from "apollo-upload-client/UploadHttpLink.mjs";
import { ApolloClient } from "@apollo/client/core";
import { InMemoryCache } from "@apollo/client/cache";

// Basic setup
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new UploadHttpLink(),
});

// Advanced configuration
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new UploadHttpLink({
    uri: "https://api.example.com/graphql",
    useGETForQueries: true,
    credentials: "include",
    headers: {
      "Authorization": "Bearer token",
    },
    fetchOptions: {
      timeout: 30000,
    },
  }),
});

// Custom file handling
import formDataAppendFile from "apollo-upload-client/formDataAppendFile.mjs";
import isExtractableFile from "apollo-upload-client/isExtractableFile.mjs";

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

const link = new UploadHttpLink({
  isExtractableFile: customIsExtractableFile,
  formDataAppendFile: (formData, fieldName, file) => {
    // Custom file appending logic
    if (file.type?.startsWith('image/')) {
      formData.append(fieldName, file, `image_${Date.now()}.${file.type.split('/')[1]}`);
    } else {
      formDataAppendFile(formData, fieldName, file);
    }
  },
});

Constructor Options

uri

  • Type: string
  • Default: "/graphql"
  • Description: The GraphQL endpoint URI where requests will be sent.

useGETForQueries

  • Type: boolean
  • Default: false
  • Description: When true, uses GET requests for queries that don't contain files. Mutations always use POST.

isExtractableFile

  • Type: ExtractableFileMatcher
  • Default: isExtractableFile from apollo-upload-client/isExtractableFile.mjs
  • Description: Function that determines which values in variables should be treated as uploadable files.

FormData

  • Type: typeof FormData
  • Default: Global FormData
  • Description: FormData constructor to use for creating multipart requests. Useful for custom FormData implementations.

formDataAppendFile

  • Type: FormDataFileAppender
  • Default: formDataAppendFile from apollo-upload-client/formDataAppendFile.mjs
  • Description: Function that handles appending files to the FormData instance.

print

  • Type: BaseHttpLink.Printer
  • Default: defaultPrinter from Apollo Client
  • Description: Function that converts GraphQL AST to string for transport.

fetch

  • Type: typeof fetch
  • Default: Global fetch
  • Description: Fetch implementation to use for HTTP requests. Useful for custom fetch implementations or polyfills.

fetchOptions

  • Type: RequestInit
  • Default: undefined
  • Description: Additional options passed to fetch. Upload-specific options will override these.

credentials

  • Type: string
  • Default: undefined
  • Description: Credentials policy for requests. Overrides any credentials setting in fetchOptions.

headers

  • Type: { [headerName: string]: string }
  • Default: undefined
  • Description: HTTP headers to include with requests. Merged with and overrides headers in fetchOptions.

includeExtensions

  • Type: boolean
  • Default: false
  • Description: Whether to include GraphQL extensions in the request payload.

includeUnusedVariables

  • Type: boolean
  • Default: false
  • Description: Whether to include GraphQL variables that aren't used in the operation.

Behavior

File Upload Detection

The link automatically scans GraphQL variables for extractable files using the configured isExtractableFile function. When files are detected:

  1. Variables are processed to extract file references
  2. A multipart request is constructed following the GraphQL multipart request specification
  3. Files are appended to FormData using the configured formDataAppendFile function
  4. The request is sent with appropriate multipart headers

Regular GraphQL Requests

When no files are detected in variables:

  1. For queries: Uses GET if useGETForQueries is true, otherwise POST
  2. For mutations: Always uses POST
  3. Variables are sent as JSON in the request body (POST) or query parameters (GET)

Error Handling

The link integrates with Apollo Client's error handling system:

  • Network errors from fetch are propagated as Apollo errors
  • GraphQL errors in the response are handled normally by Apollo Client
  • Request abortion is supported via AbortController
  • Parse errors during GET URI construction are thrown as exceptions

Request Lifecycle

  1. Variable Processing: Extract files from GraphQL variables
  2. Request Preparation: Choose request method and format based on file presence
  3. Multipart Construction: Build FormData with operations, map, and files (if files present)
  4. Fetch Execution: Send HTTP request with appropriate headers and body
  5. Response Processing: Parse response and forward to Apollo Client observers