or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

caching.mdcore-client.mderror-handling.mdindex.mdlink-system.mdmasking.mdreact-hooks.mdtesting.mdutilities.md
tile.json

utilities.mddocs/

Utilities

Utility functions and helpers for GraphQL operations, cache management, and common development tasks. Apollo Client provides a comprehensive set of utilities for working with GraphQL documents, cache operations, pagination, and development workflows.

Capabilities

GraphQL Document Utilities

Utilities for working with GraphQL documents, operations, and transformations.

/**
 * Get the main definition from a GraphQL document
 * @param queryDoc - GraphQL document
 * @returns The main operation or fragment definition
 */
function getMainDefinition(queryDoc: DocumentNode): OperationDefinitionNode | FragmentDefinitionNode;

/**
 * Check if operation is a query
 * @param document - GraphQL document
 * @returns True if document contains a query operation
 */
function isQueryOperation(document: DocumentNode): boolean;

/**
 * Check if operation is a mutation
 * @param document - GraphQL document
 * @returns True if document contains a mutation operation
 */
function isMutationOperation(document: DocumentNode): boolean;

/**
 * Check if operation is a subscription
 * @param document - GraphQL document
 * @returns True if document contains a subscription operation
 */
function isSubscriptionOperation(document: DocumentNode): boolean;

/**
 * Add __typename fields to GraphQL document
 * @param document - GraphQL document to transform
 * @returns Document with __typename fields added
 */
function addTypenameToDocument(document: DocumentNode): DocumentNode;

/**
 * Print GraphQL document to string
 * @param document - GraphQL document
 * @returns String representation of the document
 */
function print(document: DocumentNode): string;

Usage Example:

import { getMainDefinition, isQueryOperation, addTypenameToDocument } from "@apollo/client/utilities";
import { gql } from "@apollo/client";

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
    }
  }
`;

// Check operation type
const mainDef = getMainDefinition(GET_USERS);
console.log('Is query:', isQueryOperation(GET_USERS)); // true

// Add __typename automatically
const withTypename = addTypenameToDocument(GET_USERS);

Cache Utilities

Utilities for working with Apollo Client cache, references, and store operations.

/**
 * Check if value is a cache reference
 * @param obj - Value to check
 * @returns True if value is a cache reference
 */
function isReference(obj: any): obj is Reference;

/**
 * Remove __typename fields from objects
 * @param obj - Object to process
 * @returns Object without __typename fields
 */
function stripTypename(obj: any): any;

/**
 * Canonical JSON stringification for consistent cache keys
 * @param value - Value to stringify
 * @returns Canonical JSON string
 */
function canonicalStringify(value: any): string;

Usage Example:

import { isReference, stripTypename, canonicalStringify } from "@apollo/client/utilities";

// Check cache references
const userRef = { __ref: "User:123" };
console.log('Is reference:', isReference(userRef)); // true

// Remove __typename for clean data
const userData = {
  __typename: 'User',
  id: '123',
  name: 'John'
};
const clean = stripTypename(userData); // { id: '123', name: 'John' }

// Create consistent cache keys
const cacheKey = canonicalStringify({ userId: '123', type: 'profile' });

Pagination Utilities

Pre-built pagination strategies for common use cases.

/**
 * Concatenation-based pagination for infinite scrolling
 * @param keyArgs - Fields that identify unique lists
 * @returns Field policy for concat pagination
 */
function concatPagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T[]>;

/**
 * Offset/limit pagination for traditional paging
 * @param keyArgs - Fields that identify unique lists
 * @returns Field policy for offset-limit pagination
 */
function offsetLimitPagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T[]>;

/**
 * Relay-style cursor pagination
 * @param keyArgs - Fields that identify unique lists
 * @returns Field policy for Relay pagination
 */
function relayStylePagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T>;

Usage Example:

import { concatPagination, offsetLimitPagination, relayStylePagination } from "@apollo/client/utilities";
import { InMemoryCache } from "@apollo/client";

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        // Infinite scroll feed
        posts: concatPagination(["filter"]),
        
        // Traditional page-based users list
        users: offsetLimitPagination(["searchTerm"]),
        
        // Relay cursor-based comments
        comments: relayStylePagination(["postId"])
      }
    }
  }
});

Document Transformation

Advanced document transformation and caching utilities.

/**
 * Document transformer with caching capabilities
 * Enables efficient transformation of GraphQL documents with result caching
 */
class DocumentTransform {
  constructor(transform: DocumentTransformFunction, options?: DocumentTransformOptions);
  
  /**
   * Transform a GraphQL document
   * @param document - Document to transform
   * @returns Transformed document
   */
  transformDocument(document: DocumentNode): DocumentNode;
  
  /**
   * Get cache key for document transformation
   * @param document - Document to get key for
   * @returns Cache key string
   */
  getCacheKey(document: DocumentNode): DocumentTransformCacheKey;
}

type DocumentTransformFunction = (document: DocumentNode) => DocumentNode;
type DocumentTransformCacheKey = string;

interface DocumentTransformOptions {
  /** Cache transformation results */
  cache?: boolean;
  /** Custom cache key function */
  getCacheKey?: (document: DocumentNode) => DocumentTransformCacheKey;
}

Usage Example:

import { DocumentTransform } from "@apollo/client/utilities";

// Create custom document transformer
const addMetadataTransform = new DocumentTransform(
  (doc) => {
    // Add custom metadata to operations
    return {
      ...doc,
      definitions: doc.definitions.map(def => ({
        ...def,
        directives: [
          ...(def.directives || []),
          {
            kind: 'Directive',
            name: { kind: 'Name', value: 'metadata' }
          }
        ]
      }))
    };
  },
  { cache: true }
);

const transformedDoc = addMetadataTransform.transformDocument(myQuery);

Network Request Utilities

Utilities for monitoring and managing network request states.

/**
 * Check if network request is currently in flight
 * @param networkStatus - Current network status
 * @returns True if request is active
 */
function isNetworkRequestInFlight(networkStatus: NetworkStatus): boolean;

/**
 * Check if network request has settled (completed or errored)
 * @param networkStatus - Current network status
 * @returns True if request has finished
 */
function isNetworkRequestSettled(networkStatus: NetworkStatus): boolean;

Usage Example:

import { isNetworkRequestInFlight, isNetworkRequestSettled } from "@apollo/client/utilities";
import { NetworkStatus } from "@apollo/client";

function RequestStatus({ networkStatus }: { networkStatus: NetworkStatus }) {
  if (isNetworkRequestInFlight(networkStatus)) {
    return <LoadingSpinner />;
  }
  
  if (isNetworkRequestSettled(networkStatus)) {
    return <div>Request completed</div>;
  }
  
  return <div>Request pending</div>;
}

Development Utilities

Utilities for development, debugging, and performance monitoring.

/**
 * Get current cache sizes for monitoring and debugging
 * @returns Object containing cache size information
 */
function cacheSizes(): CacheSizes;

interface CacheSizes {
  /** Size of the root store */
  root: number;
  /** Size of optimistic layers */
  optimistic: number;
  /** Total cache size */
  total: number;
}

/**
 * Check if execution result has expected format
 * @param result - Execution result to validate
 * @returns True if result is properly formatted
 */
function isFormattedExecutionResult(result: any): result is ExecutionResult;

Usage Example:

import { cacheSizes } from "@apollo/client/utilities";

// Monitor cache performance
function logCacheStats() {
  const sizes = cacheSizes();
  console.log('Cache sizes:', {
    root: `${sizes.root} objects`,
    optimistic: `${sizes.optimistic} layers`,
    total: `${sizes.total} total objects`
  });
}

// Call periodically to monitor cache growth
setInterval(logCacheStats, 30000);

Types

interface Reference {
  readonly __ref: string;
}

interface StoreObject {
  __typename?: string;
  [storeFieldName: string]: StoreValue;
}

type StoreValue = 
  | number
  | string
  | boolean
  | null
  | undefined
  | void
  | Object
  | Reference
  | (number | string | boolean | Reference | Object | null)[];

type AsStoreObject<T> = T & StoreObject;

type DeepPartial<T> = T extends object ? {
  [P in keyof T]?: DeepPartial<T[P]>;
} : T;

/** Higher-kinded type for advanced type manipulation */
interface HKT<T = unknown> {
  readonly _T: T;
}