CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/npm-graphql-yoga

Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience

Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

Helper functions for caching, GraphiQL rendering, and common server operations. These utilities support performance optimization and development workflow enhancements.

Capabilities

LRU Cache Creation

Function to create configurable LRU (Least Recently Used) cache instances for performance optimization.

/**
 * Creates a configurable LRU cache instance
 * @param options - Cache configuration options
 * @returns LRU cache instance
 */
function createLRUCache<T extends {}>(options?: LRUCacheOptions): LRUCache<T>;

/**
 * LRU cache configuration options
 */
interface LRUCacheOptions {
  /** Maximum number of items to store (default: 1024) */
  max?: number;
  /** Time to live for items in milliseconds (default: 3600000 / 1 hour) */
  ttl?: number;
}

/**
 * LRU cache instance type
 */
type LRUCache<T extends {}> = LRU<string, T>;

Usage Examples:

import { createLRUCache } from "graphql-yoga";

// Default cache configuration
const cache = createLRUCache();

// Custom cache configuration
const customCache = createLRUCache({
  max: 5000,          // Store up to 5000 items
  ttl: 1800000        // 30 minutes TTL
});

// Use cache in resolvers
interface UserData {
  id: string;
  name: string;
  email: string;
}

const userCache = createLRUCache<UserData>({
  max: 1000,
  ttl: 600000 // 10 minutes
});

const resolvers = {
  Query: {
    user: async (_, { id }) => {
      // Check cache first
      let user = userCache.get(id);
      
      if (!user) {
        // Cache miss - fetch from database
        user = await fetchUserFromDatabase(id);
        if (user) {
          userCache.set(id, user);
        }
      }
      
      return user;
    }
  }
};

// Use cache for GraphQL parsing/validation
const parserCache = createLRUCache<any>({
  max: 2000,
  ttl: 3600000
});

const yoga = createYoga({
  plugins: [
    {
      onRequestParse({ request }) {
        const query = request.body?.query;
        if (query) {
          const cached = parserCache.get(query);
          if (cached) {
            console.log('Using cached parsed query');
            return cached;
          }
        }
      }
    }
  ]
});

GraphiQL Rendering

Function to render GraphiQL HTML interface with custom configuration.

/**
 * Renders GraphiQL HTML interface
 * @param opts - GraphiQL rendering options
 * @returns GraphiQL HTML string
 */
function renderGraphiQL(opts: GraphiQLRendererOptions): string;

/**
 * GraphiQL rendering configuration options
 */
interface GraphiQLRendererOptions {
  /** GraphQL endpoint path (default: "/graphql") */
  endpoint?: string;
  /** Default query to display */
  defaultQuery?: string;
  /** Initial headers in JSON string format */
  headers?: string;
  /** Request credentials mode */
  credentials?: RequestCredentials;
  /** Page title for GraphiQL */
  title?: string;
  /** Subscription protocol to use */
  subscriptionsProtocol?: 'SSE' | 'GRAPHQL_SSE' | 'WS' | 'LEGACY_WS';
  /** Additional headers to always include */
  additionalHeaders?: Record<string, string>;
}

Usage Examples:

import { renderGraphiQL } from "graphql-yoga";

// Basic GraphiQL rendering
const basicHTML = renderGraphiQL({
  endpoint: '/graphql'
});

// Custom GraphiQL with configuration
const customHTML = renderGraphiQL({
  endpoint: '/api/graphql',
  title: 'My API Explorer',
  defaultQuery: `
    query GetUsers {
      users {
        id
        name
        email
      }
    }
  `,
  headers: JSON.stringify({
    'Authorization': 'Bearer your-token-here',
    'X-Client-Version': '1.0.0'
  }),
  credentials: 'include',
  subscriptionsProtocol: 'SSE',
  additionalHeaders: {
    'X-Custom-Header': 'value'
  }
});

// Use in custom route handler
const customGraphiQLHandler = (request: Request, fetchAPI: FetchAPI) => {
  const html = renderGraphiQL({
    endpoint: '/graphql',
    title: 'Development API',
    defaultQuery: 'query { __schema { types { name } } }'
  });
  
  return new fetchAPI.Response(html, {
    headers: { 'Content-Type': 'text/html' }
  });
};

// Custom GraphiQL plugin
const customGraphiQLPlugin: Plugin = {
  onRequest({ request, endResponse, fetchAPI, url }) {
    if (url.pathname === '/explorer' && request.method === 'GET') {
      const html = renderGraphiQL({
        endpoint: '/graphql',
        title: 'GraphQL Explorer',
        subscriptionsProtocol: 'SSE'
      });
      
      endResponse(new fetchAPI.Response(html, {
        headers: { 'Content-Type': 'text/html; charset=utf-8' }
      }));
    }
  }
};

GraphiQL Detection

Function to determine if a request should receive the GraphiQL interface.

/**
 * Determines if request should receive GraphiQL interface
 * @param request - HTTP request to check
 * @returns Whether to render GraphiQL
 */
function shouldRenderGraphiQL(request: Request): boolean;

Usage Examples:

import { shouldRenderGraphiQL, renderGraphiQL } from "graphql-yoga";

// Custom GraphiQL handling
const graphiQLHandler = (request: Request, fetchAPI: FetchAPI) => {
  if (shouldRenderGraphiQL(request)) {
    const html = renderGraphiQL({ endpoint: '/graphql' });
    return new fetchAPI.Response(html, {
      headers: { 'Content-Type': 'text/html' }
    });
  }
  
  return null; // Not a GraphiQL request
};

// Conditional GraphiQL plugin
const conditionalGraphiQLPlugin: Plugin = {
  onRequest({ request, endResponse, fetchAPI, url }) {
    if (url.pathname === '/graphql' && shouldRenderGraphiQL(request)) {
      // Only serve GraphiQL for appropriate requests (GET with HTML accept header)
      const html = renderGraphiQL({
        endpoint: '/graphql',
        title: 'API Explorer'
      });
      
      endResponse(new fetchAPI.Response(html, {
        headers: { 'Content-Type': 'text/html' }
      }));
    }
  }
};

// Environment-based GraphiQL
const productionSafeGraphiQL: Plugin = {
  onRequest({ request, endResponse, fetchAPI, url }) {
    const isDevelopment = process.env.NODE_ENV === 'development';
    const isGraphiQLRequest = shouldRenderGraphiQL(request);
    
    if (url.pathname === '/graphql' && isGraphiQLRequest) {
      if (!isDevelopment) {
        // Redirect to documentation in production
        endResponse(new fetchAPI.Response(null, {
          status: 302,
          headers: { 'Location': '/docs' }
        }));
      } else {
        // Serve GraphiQL in development
        const html = renderGraphiQL({ endpoint: '/graphql' });
        endResponse(new fetchAPI.Response(html, {
          headers: { 'Content-Type': 'text/html' }
        }));
      }
    }
  }
};

Type Utilities

Utility types for common patterns in GraphQL Yoga applications.

/**
 * Utility type for optional single value or array
 */
type MaybeArray<T> = T | T[];

/**
 * Utility type for synchronous or asynchronous values
 */
type PromiseOrValue<T> = T | Promise<T>;

/**
 * Utility type for optional values
 */
type Maybe<T> = T | null | undefined;

/**
 * Utility type for optional object properties
 */
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

/**
 * Utility type for object spread operations
 */
type Spread<T1, T2> = T1 & T2;

Usage Examples:

// Using utility types in function signatures
function processData<T>(input: MaybeArray<T>): T[] {
  return Array.isArray(input) ? input : [input];
}

async function resolveValue<T>(value: PromiseOrValue<T>): Promise<T> {
  return await value;
}

function handleOptionalUser(user: Maybe<User>): string {
  return user?.name ?? 'Anonymous';
}

// Configuration with optional properties
interface ServerConfig {
  port: number;
  host: string;
  ssl?: boolean;
  timeout?: number;
}

type MinimalConfig = Optional<ServerConfig, 'host' | 'ssl' | 'timeout'>;

const config: MinimalConfig = {
  port: 4000
  // host, ssl, timeout are optional
};

// Context merging with type safety
type BaseContext = {
  request: Request;
  timestamp: number;
};

type UserContext = {
  user: User;
  permissions: string[];
};

type MergedContext = Spread<BaseContext, UserContext>;

const createContext = (base: BaseContext, user: UserContext): MergedContext => {
  return { ...base, ...user };
};

Performance Utilities

Additional utilities for monitoring and optimizing GraphQL Yoga performance.

Usage Examples:

// Performance monitoring with LRU cache
const metricsCache = createLRUCache<{
  count: number;
  totalTime: number;
  avgTime: number;
}>({
  max: 1000,
  ttl: 300000 // 5 minutes
});

const performancePlugin: Plugin = {
  onParams({ params, setParams }) {
    const startTime = Date.now();
    const operationName = params.operationName || 'anonymous';
    
    // Store start time in extensions
    setParams({
      ...params,
      extensions: {
        ...params.extensions,
        startTime
      }
    });
  },
  
  onResultProcess({ result, request }) {
    if ('extensions' in result && result.extensions?.startTime) {
      const duration = Date.now() - result.extensions.startTime;
      const operationName = 'operationName'; // Extract from result if available
      
      // Update metrics
      const existing = metricsCache.get(operationName) || { count: 0, totalTime: 0, avgTime: 0 };
      const updated = {
        count: existing.count + 1,
        totalTime: existing.totalTime + duration,
        avgTime: (existing.totalTime + duration) / (existing.count + 1)
      };
      
      metricsCache.set(operationName, updated);
      
      console.log(`Operation ${operationName} took ${duration}ms (avg: ${updated.avgTime.toFixed(2)}ms)`);
    }
  }
};

// Cache warming utility
async function warmupCache<T>(
  cache: LRUCache<T>,
  dataProvider: () => Promise<Array<{ key: string; value: T }>>
) {
  const data = await dataProvider();
  
  for (const { key, value } of data) {
    cache.set(key, value);
  }
  
  console.log(`Cache warmed up with ${data.length} items`);
}

// Usage
const userCache = createLRUCache<User>({ max: 10000, ttl: 600000 });

await warmupCache(userCache, async () => {
  const users = await fetchFrequentlyAccessedUsers();
  return users.map(user => ({ key: user.id, value: user }));
});
tessl i tessl/npm-graphql-yoga@4.0.0

docs

built-in-plugins.md

error-handling.md

index.md

plugin-system.md

schema-integration.md

server-configuration.md

subscription-support.md

utility-functions.md

tile.json