Apollo Utilities is a TypeScript library that provides essential utilities for working with GraphQL Abstract Syntax Trees (ASTs). It offers comprehensive functions for manipulating fragments, handling directives, transforming documents, extracting AST information, and managing store utilities for caching operations.
npm install apollo-utilitiesimport {
// Directive utilities
shouldInclude,
getDirectiveNames,
hasDirectives,
// Fragment utilities
getFragmentQueryDocument,
// AST extraction
getOperationDefinition,
getFragmentDefinitions,
getMainDefinition,
// Document transformation
removeDirectivesFromDocument,
addTypenameToDocument,
// Store utilities
storeKeyNameFromField,
argumentsObjectFromField,
isField,
// Utility functions
cloneDeep,
isEqual,
assign,
mergeDeep
} from "apollo-utilities";For CommonJS:
const {
shouldInclude,
getOperationDefinition,
removeDirectivesFromDocument,
storeKeyNameFromField,
cloneDeep
} = require("apollo-utilities");import {
getOperationDefinition,
shouldInclude,
storeKeyNameFromField,
addTypenameToDocument
} from "apollo-utilities";
import { parse } from "graphql";
// Parse a GraphQL query
const query = parse(`
query GetUser($id: ID!) {
user(id: $id) @include(if: $showUser) {
name
email
}
}
`);
// Extract operation definition
const operation = getOperationDefinition(query);
console.log(operation?.operation); // "query"
// Check if a field should be included based on directives
const userField = operation?.selectionSet.selections[0];
const variables = { showUser: true };
const include = shouldInclude(userField, variables);
console.log(include); // true
// Add __typename fields for caching
const queryWithTypename = addTypenameToDocument(query);
// Generate store keys for fields
const field = userField;
const storeKey = storeKeyNameFromField(field, variables);
console.log(storeKey); // "user({"id":"$id"})"Apollo Utilities is organized into several key modules:
Functions for working with GraphQL directives including conditional inclusion (@skip/@include), client-side directives (@client), and directive extraction.
function shouldInclude(
selection: SelectionNode,
variables?: { [name: string]: any }
): boolean;
function getDirectiveNames(doc: DocumentNode): string[];
function hasDirectives(names: string[], doc: DocumentNode): boolean;Utilities for manipulating GraphQL fragments and converting them into executable query documents.
function getFragmentQueryDocument(
document: DocumentNode,
fragmentName?: string
): DocumentNode;Functions for extracting operations, fragments, and other components from GraphQL documents, plus utilities for analyzing document structure.
function getOperationDefinition(doc: DocumentNode): OperationDefinitionNode | undefined;
function getFragmentDefinitions(doc: DocumentNode): FragmentDefinitionNode[];
function getMainDefinition(
queryDoc: DocumentNode
): OperationDefinitionNode | FragmentDefinitionNode;
interface FragmentMap {
[fragmentName: string]: FragmentDefinitionNode;
}
function createFragmentMap(fragments?: FragmentDefinitionNode[]): FragmentMap;Functions for modifying GraphQL documents including removing directives, adding __typename fields, and transforming document structure.
function removeDirectivesFromDocument(
directives: RemoveDirectiveConfig[],
doc: DocumentNode
): DocumentNode | null;
function addTypenameToDocument(doc: DocumentNode): DocumentNode;
function buildQueryFromSelectionSet(document: DocumentNode): DocumentNode;
interface RemoveDirectiveConfig {
name?: string;
test?: (node: DirectiveNode) => boolean;
remove?: boolean;
}Functions for generating store keys, extracting field arguments, and working with cached data structures in GraphQL clients.
function storeKeyNameFromField(field: FieldNode, variables?: Object): string;
function argumentsObjectFromField(
field: FieldNode | DirectiveNode,
variables: Object
): Object;
function isField(selection: SelectionNode): selection is FieldNode;
function valueFromNode(
node: ValueNode,
onVariable?: (node: VariableNode) => any
): any;General-purpose utility functions for object manipulation, environment detection, error handling, and data processing.
function cloneDeep<T>(value: T): T;
function isEqual(a: any, b: any): boolean;
function assign(target: any, ...sources: Array<any>): any;
function mergeDeep<T extends any[]>(...sources: T): TupleToIntersection<T>;
function getEnv(): string | undefined;
function isProduction(): boolean;// Store value types
interface IdValue {
type: 'id';
id: string;
generated: boolean;
typename: string | undefined;
}
interface JsonValue {
type: 'json';
json: any;
}
type StoreValue =
| number
| string
| string[]
| IdValue
| ListValue
| JsonValue
| null
| undefined
| void
| Object;
// Directive types
type DirectiveInfo = {
[fieldName: string]: { [argName: string]: any };
};
type InclusionDirectives = Array<{
directive: DirectiveNode;
ifArgument: ArgumentNode;
}>;
// Fragment types
interface FragmentMap {
[fragmentName: string]: FragmentDefinitionNode;
}
// Configuration types
interface RemoveNodeConfig<N> {
name?: string;
test?: (node: N) => boolean;
remove?: boolean;
}
interface GetNodeConfig<N> {
name?: string;
test?: (node: N) => boolean;
}