Functions for generating store keys, extracting field arguments, and working with cached data structures in GraphQL clients.
Generates a unique store key for a GraphQL field, incorporating field name, arguments, and relevant directives.
/**
* Generate store key for a GraphQL field
* @param field - GraphQL field node
* @param variables - Variable values for argument resolution
* @returns Unique store key string for the field
*/
function storeKeyNameFromField(field: FieldNode, variables?: Object): string;Usage Examples:
import { storeKeyNameFromField } from "apollo-utilities";
import { parse } from "graphql";
const query = parse(`
query GetUser($id: ID!, $includeEmail: Boolean!) {
user(id: $id, active: true) @connection(key: "users", filter: ["active"]) {
name
email @include(if: $includeEmail)
}
}
`);
const operation = getOperationDefinition(query);
const userField = operation.selectionSet.selections[0];
const variables = { id: "123", includeEmail: true };
const storeKey = storeKeyNameFromField(userField, variables);
console.log(storeKey); // "users({"active":true})" (using @connection key)
// Without @connection directive
const simpleQuery = parse(`
query {
posts(limit: 10, offset: 0) {
title
}
}
`);
const postsField = getOperationDefinition(simpleQuery).selectionSet.selections[0];
const postsKey = storeKeyNameFromField(postsField);
console.log(postsKey); // "posts({"limit":10,"offset":0})"
// Field without arguments
const nameQuery = parse(`
query {
user {
name
}
}
`);
const nameField = getOperationDefinition(nameQuery).selectionSet.selections[0];
const nameKey = storeKeyNameFromField(nameField);
console.log(nameKey); // "user"Lower-level function for generating store keys from field name, arguments, and directives.
/**
* Generate store key from field components
* @param fieldName - Name of the field
* @param args - Field arguments object (optional)
* @param directives - Field directives object (optional)
* @returns Store key string
*/
function getStoreKeyName(
fieldName: string,
args?: Object,
directives?: Directives
): string;Usage Examples:
import { getStoreKeyName } from "apollo-utilities";
// Simple field name
const key1 = getStoreKeyName("user");
console.log(key1); // "user"
// Field with arguments
const key2 = getStoreKeyName("posts", { limit: 10, status: "published" });
console.log(key2); // "posts({"limit":10,"status":"published"})"
// Field with @connection directive
const key3 = getStoreKeyName("comments", { postId: "123" }, {
connection: { key: "postComments", filter: ["postId"] }
});
console.log(key3); // "postComments({"postId":"123"})"
// Field with custom directive
const key4 = getStoreKeyName("data", {}, {
cache: { ttl: 300 }
});
console.log(key4); // "data@cache({"ttl":300})"Extracts field arguments as a plain JavaScript object, resolving variables to their values.
/**
* Extract field arguments as object
* @param field - GraphQL field or directive node
* @param variables - Variable values for resolution
* @returns Arguments object or null if no arguments
*/
function argumentsObjectFromField(
field: FieldNode | DirectiveNode,
variables: Object
): Object | null;Usage Examples:
import { argumentsObjectFromField } from "apollo-utilities";
import { parse } from "graphql";
const query = parse(`
query GetPosts($limit: Int, $status: String) {
posts(limit: $limit, offset: 0, status: $status, featured: true) {
title
}
}
`);
const postsField = getOperationDefinition(query).selectionSet.selections[0];
const variables = { limit: 20, status: "published" };
const args = argumentsObjectFromField(postsField, variables);
console.log(args);
// {
// limit: 20, // resolved from variable
// offset: 0, // literal value
// status: "published", // resolved from variable
// featured: true // literal value
// }
// Field without arguments
const simpleQuery = parse(`query { user { name } }`);
const userField = getOperationDefinition(simpleQuery).selectionSet.selections[0];
const noArgs = argumentsObjectFromField(userField, {});
console.log(noArgs); // nullGets the result key name for a field, using the alias if present, otherwise the field name.
/**
* Get result key name for field (alias or field name)
* @param field - GraphQL field node
* @returns Key name for field in result object
*/
function resultKeyNameFromField(field: FieldNode): string;Usage Examples:
import { resultKeyNameFromField } from "apollo-utilities";
import { parse } from "graphql";
const query = parse(`
query {
user {
fullName: name
email
userPosts: posts {
title
}
}
}
`);
const userSelection = getOperationDefinition(query).selectionSet.selections[0];
const userFields = userSelection.selectionSet.selections;
console.log(resultKeyNameFromField(userFields[0])); // "fullName" (uses alias)
console.log(resultKeyNameFromField(userFields[1])); // "email" (uses field name)
console.log(resultKeyNameFromField(userFields[2])); // "userPosts" (uses alias)Converts a GraphQL value node to its corresponding JavaScript value.
/**
* Convert GraphQL value node to JavaScript value
* @param node - GraphQL value node to convert
* @param onVariable - Function to resolve variable values (optional)
* @returns JavaScript representation of the value
*/
function valueFromNode(
node: ValueNode,
onVariable?: (node: VariableNode) => any
): any;Usage Examples:
import { valueFromNode } from "apollo-utilities";
// Assuming we have parsed value nodes from GraphQL arguments
// String value
const stringValue = { kind: "StringValue", value: "hello" };
console.log(valueFromNode(stringValue)); // "hello"
// Number values
const intValue = { kind: "IntValue", value: "42" };
const floatValue = { kind: "FloatValue", value: "3.14" };
console.log(valueFromNode(intValue)); // 42
console.log(valueFromNode(floatValue)); // 3.14
// Boolean value
const boolValue = { kind: "BooleanValue", value: true };
console.log(valueFromNode(boolValue)); // true
// List value
const listValue = {
kind: "ListValue",
values: [
{ kind: "StringValue", value: "a" },
{ kind: "StringValue", value: "b" }
]
};
console.log(valueFromNode(listValue)); // ["a", "b"]
// Object value
const objectValue = {
kind: "ObjectValue",
fields: [
{
name: { value: "name" },
value: { kind: "StringValue", value: "John" }
},
{
name: { value: "age" },
value: { kind: "IntValue", value: "30" }
}
]
};
console.log(valueFromNode(objectValue)); // { name: "John", age: 30 }
// Variable value with resolver
const variableValue = {
kind: "Variable",
name: { value: "userId" }
};
const variableResolver = (varNode) => {
const variables = { userId: "123" };
return variables[varNode.name.value];
};
console.log(valueFromNode(variableValue, variableResolver)); // "123"Converts a GraphQL value node to an object property, handling nested objects and variable resolution.
/**
* Convert GraphQL value to object property
* @param argObj - Target object to set property on
* @param name - Property name node
* @param value - Value node to convert
* @param variables - Variable values for resolution (optional)
*/
function valueToObjectRepresentation(
argObj: any,
name: NameNode,
value: ValueNode,
variables?: Object
): void;Type guard functions for identifying GraphQL selection node types.
/**
* Check if selection is a field node
* @param selection - GraphQL selection node
* @returns true if selection is a field
*/
function isField(selection: SelectionNode): selection is FieldNode;
/**
* Check if selection is an inline fragment
* @param selection - GraphQL selection node
* @returns true if selection is an inline fragment
*/
function isInlineFragment(selection: SelectionNode): selection is InlineFragmentNode;Functions for identifying Apollo store value types.
/**
* Check if value is an ID value object
* @param idObject - Value to check
* @returns true if value is IdValue type
*/
function isIdValue(idObject: StoreValue): idObject is IdValue;
/**
* Check if value is a JSON value object
* @param jsonObject - Value to check
* @returns true if value is JsonValue type
*/
function isJsonValue(jsonObject: StoreValue): jsonObject is JsonValue;
/**
* Check if GraphQL value is a scalar type
* @param value - GraphQL value node
* @returns true if value is string, boolean, or enum
*/
function isScalarValue(value: ValueNode): value is ScalarValue;
/**
* Check if GraphQL value is a number type
* @param value - GraphQL value node
* @returns true if value is int or float
*/
function isNumberValue(value: ValueNode): value is NumberValue;Functions for creating Apollo store value objects.
/**
* Create an ID value object for store
* @param idConfig - ID configuration (string or object)
* @param generated - Whether ID was generated (default: false)
* @returns IdValue object for store
*/
function toIdValue(idConfig: string | IdConfig, generated?: boolean): IdValue;Usage Example:
import { toIdValue } from "apollo-utilities";
// Simple string ID
const id1 = toIdValue("user-123");
console.log(id1);
// {
// type: "id",
// id: "user-123",
// generated: false,
// typename: undefined
// }
// ID with typename
const id2 = toIdValue({ id: "user-123", typename: "User" }, true);
console.log(id2);
// {
// type: "id",
// id: "user-123",
// generated: true,
// typename: "User"
// }interface IdValue {
type: 'id';
id: string;
generated: boolean;
typename: string | undefined;
}
interface JsonValue {
type: 'json';
json: any;
}
type ListValue = Array<null | IdValue>;
type StoreValue =
| number
| string
| string[]
| IdValue
| ListValue
| JsonValue
| null
| undefined
| void
| Object;
type ScalarValue = StringValueNode | BooleanValueNode | EnumValueNode;
type NumberValue = IntValueNode | FloatValueNode;
interface Directives {
[directiveName: string]: {
[argName: string]: any;
};
}
interface IdConfig {
id: string;
typename: string | undefined;
}
type VariableValue = (node: VariableNode) => any;