CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-tools--utils

Common package containing utils and types for GraphQL tools

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

directives.mddocs/

Directives

Directive extraction, extension handling, and built-in directive support for GraphQL schema processing. These utilities enable comprehensive directive-based schema analysis and transformation workflows.

Capabilities

Directive Extraction

Extract directive information from GraphQL schema elements.

/**
 * Get all directives applied to a schema element
 * @param schema - The GraphQL schema
 * @param node - The AST node or schema element
 * @returns Array of directive usage information
 */
function getDirectives(
  schema: GraphQLSchema,
  node: ASTNode | GraphQLNamedType | GraphQLField<any, any> | GraphQLArgument | GraphQLEnumValue
): DirectiveUsage[];

/**
 * Get a specific directive applied to a schema element
 * @param schema - The GraphQL schema  
 * @param node - The AST node or schema element
 * @param directiveName - Name of the directive to find
 * @returns Directive usage information or undefined if not found
 */
function getDirective(
  schema: GraphQLSchema,
  node: ASTNode | GraphQLNamedType | GraphQLField<any, any> | GraphQLArgument | GraphQLEnumValue,
  directiveName: string
): DirectiveUsage | undefined;

interface DirectiveUsage {
  name: string;
  args: Record<string, any>;
}

Usage Examples:

import { getDirectives, getDirective } from "@graphql-tools/utils";

// Get all directives on a field
const userNameField = schema.getType('User').getFields().name;
const directives = getDirectives(schema, userNameField);
console.log('Directives on User.name:', directives);
// Result: [{ name: 'deprecated', args: { reason: 'Use displayName instead' } }]

// Get specific directive
const deprecatedDirective = getDirective(schema, userNameField, 'deprecated');
if (deprecatedDirective) {
  console.log('Deprecation reason:', deprecatedDirective.args.reason);
}

// Check for custom directives
const authDirective = getDirective(schema, userNameField, 'auth');
if (authDirective) {
  console.log('Auth requirements:', authDirective.args);
}

Extension-Based Directives

Work with directives stored in schema extensions.

/**
 * Get directives from schema extension objects
 * @param extensions - The extensions object
 * @param directiveName - Optional specific directive name
 * @returns Directive usage information
 */
function getDirectivesInExtensions(
  extensions: Record<string, any>,
  directiveName?: string
): DirectiveUsage[] | DirectiveUsage | undefined;

/**
 * Get a specific directive from extensions
 * @param extensions - The extensions object
 * @param directiveName - Name of the directive to find
 * @returns Directive usage information or undefined
 */
function getDirectiveInExtensions(
  extensions: Record<string, any>,
  directiveName: string
): DirectiveUsage | undefined;

Usage Extensions:

import { getDirectivesInExtensions, getDirectiveInExtensions } from "@graphql-tools/utils";

// Get directives from field extensions
const fieldConfig = {
  type: GraphQLString,
  extensions: {
    directives: {
      deprecated: { reason: 'Use newField instead' },
      auth: { requires: 'USER' }
    }
  }
};

const directives = getDirectivesInExtensions(fieldConfig.extensions);
console.log('Extension directives:', directives);

const authDirective = getDirectiveInExtensions(fieldConfig.extensions, 'auth');
console.log('Auth directive:', authDirective);

Targeted Directive Discovery

Find schema elements that have specific directives applied.

/**
 * Get all fields in a schema that have directives applied
 * @param schema - The GraphQL schema
 * @param directiveName - Optional specific directive name to filter by
 * @returns Nested object mapping type names to field names to directive arrays
 */
function getFieldsWithDirectives(
  schema: GraphQLSchema,
  directiveName?: string
): Record<string, Record<string, DirectiveUsage[]>>;

/**
 * Get all arguments in a schema that have directives applied
 * @param schema - The GraphQL schema
 * @param directiveName - Optional specific directive name to filter by  
 * @returns Nested object mapping type names to field names to argument names to directive arrays
 */
function getArgumentsWithDirectives(
  schema: GraphQLSchema,
  directiveName?: string
): Record<string, Record<string, Record<string, DirectiveUsage[]>>>;

Usage Examples:

import { getFieldsWithDirectives, getArgumentsWithDirectives } from "@graphql-tools/utils";

// Find all deprecated fields
const deprecatedFields = getFieldsWithDirectives(schema, 'deprecated');
Object.entries(deprecatedFields).forEach(([typeName, fields]) => {
  Object.entries(fields).forEach(([fieldName, directives]) => {
    console.log(`${typeName}.${fieldName} is deprecated:`, directives[0].args.reason);
  });
});

// Find all fields with any directives
const allFieldsWithDirectives = getFieldsWithDirectives(schema);
console.log('Fields with directives:', allFieldsWithDirectives);

// Find arguments with validation directives
const argsWithValidation = getArgumentsWithDirectives(schema, 'validate');
Object.entries(argsWithValidation).forEach(([typeName, fields]) => {
  Object.entries(fields).forEach(([fieldName, args]) => {
    Object.entries(args).forEach(([argName, directives]) => {
      console.log(`${typeName}.${fieldName}(${argName}) has validation:`, directives);
    });
  });
});

Directive Extensions

Extract and manage directive-based extensions and metadata.

/**
 * Get directive-based extensions from schema elements
 * @param schema - The GraphQL schema
 * @param typeName - Name of the type to examine
 * @param fieldName - Optional field name
 * @param argName - Optional argument name
 * @returns Extensions object with directive information
 */
function getDirectiveExtensions(
  schema: GraphQLSchema,
  typeName: string,
  fieldName?: string,
  argName?: string
): Record<string, any>;

Usage Examples:

import { getDirectiveExtensions } from "@graphql-tools/utils";

// Get type-level directive extensions
const userTypeExtensions = getDirectiveExtensions(schema, 'User');
console.log('User type extensions:', userTypeExtensions);

// Get field-level directive extensions  
const fieldExtensions = getDirectiveExtensions(schema, 'User', 'name');
console.log('User.name extensions:', fieldExtensions);

// Get argument-level directive extensions
const argExtensions = getDirectiveExtensions(schema, 'Query', 'user', 'id');
console.log('Query.user(id) extensions:', argExtensions);

Built-in Directive Support

Work with GraphQL's built-in directives and location enums.

/**
 * Enum for directive locations as defined in GraphQL specification
 */
enum DirectiveLocation {
  // Request Directives
  QUERY = 'QUERY',
  MUTATION = 'MUTATION', 
  SUBSCRIPTION = 'SUBSCRIPTION',
  FIELD = 'FIELD',
  FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION',
  FRAGMENT_SPREAD = 'FRAGMENT_SPREAD',
  INLINE_FRAGMENT = 'INLINE_FRAGMENT',
  VARIABLE_DEFINITION = 'VARIABLE_DEFINITION',
  
  // Type System Directives
  SCHEMA = 'SCHEMA',
  SCALAR = 'SCALAR',
  OBJECT = 'OBJECT',
  FIELD_DEFINITION = 'FIELD_DEFINITION',
  ARGUMENT_DEFINITION = 'ARGUMENT_DEFINITION',
  INTERFACE = 'INTERFACE',
  UNION = 'UNION',
  ENUM = 'ENUM',
  ENUM_VALUE = 'ENUM_VALUE',
  INPUT_OBJECT = 'INPUT_OBJECT',
  INPUT_FIELD_DEFINITION = 'INPUT_FIELD_DEFINITION'
}

/**
 * Type alias for directive location values
 */
type DirectiveLocationEnum = keyof typeof DirectiveLocation;

Directive Annotation

Create and manage directive annotations for schema elements.

/**
 * Interface for directive annotations
 */
interface DirectiveAnnotation {
  name: string;
  args?: Record<string, any>;
}

/**
 * Apply directive annotations to schema elements
 * @param element - The schema element to annotate
 * @param directives - Array of directive annotations to apply
 * @returns Element with applied directive annotations
 */
function applyDirectiveAnnotations<T>(
  element: T,
  directives: DirectiveAnnotation[]
): T;

Usage Examples:

import { DirectiveLocation, DirectiveAnnotation } from "@graphql-tools/utils";

// Create custom directive definition
const authDirective = new GraphQLDirective({
  name: 'auth',
  locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT],
  args: {
    requires: {
      type: new GraphQLEnumType({
        name: 'Role',
        values: {
          ADMIN: { value: 'ADMIN' },
          USER: { value: 'USER' }
        }
      })
    }
  }
});

// Apply directive annotations
const annotatedField = applyDirectiveAnnotations(fieldConfig, [
  { name: 'auth', args: { requires: 'ADMIN' } },
  { name: 'deprecated', args: { reason: 'Use newField instead' } }
]);

Schema Directive Processing

Process directives across entire schemas for analysis and transformation.

/**
 * Process all directives in a schema with a visitor function
 * @param schema - The GraphQL schema to process
 * @param visitor - Function called for each directive found
 */
function visitSchemaDirectives(
  schema: GraphQLSchema,
  visitor: (
    directive: DirectiveUsage,
    location: DirectiveLocation,
    element: GraphQLNamedType | GraphQLField<any, any> | GraphQLArgument | GraphQLEnumValue
  ) => void
): void;

/**
 * Extract all unique directive names used in a schema
 * @param schema - The GraphQL schema to analyze
 * @returns Set of directive names found in the schema
 */
function getSchemaDirectiveNames(schema: GraphQLSchema): Set<string>;

Usage Examples:

import { visitSchemaDirectives, getSchemaDirectiveNames } from "@graphql-tools/utils";

// Process all directives in schema
visitSchemaDirectives(schema, (directive, location, element) => {
  console.log(`Found ${directive.name} directive at ${location}:`, directive.args);
  
  // Handle specific directives
  if (directive.name === 'auth') {
    console.log('Auth directive requires:', directive.args.requires);
  }
});

// Get all directive names used
const directiveNames = getSchemaDirectiveNames(schema);
console.log('Directives used in schema:', Array.from(directiveNames));

docs

ast-operations.md

directives.md

execution-resolution.md

field-type-operations.md

index.md

schema-transformation.md

utilities.md

tile.json