Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

graphql-performance

БесплатноБез исполняемых скриптовНе проверен

Use when optimizing GraphQL API performance with query complexity analysis, batching, caching strategies, depth limiting, monitoring, and database optimization.

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

GraphQL Performance

Apply GraphQL performance optimization techniques to create efficient, scalable APIs. This skill covers query complexity analysis, depth limiting, batching and caching strategies, DataLoader optimization, monitoring, tracing, and database query optimization.

Query Complexity Analysis

Query complexity analysis prevents expensive queries from overwhelming your server by calculating and limiting the computational cost.

import { GraphQLError } from 'graphql';
import { ApolloServer } from '@apollo/server';

// Complexity calculator
const getComplexity = (field, childComplexity, args) => {
  // Base complexity for field
  let complexity = 1;

  // List multiplier based on limit argument
  if (args.limit) {
    complexity = args.limit;
  } else if (args.first) {
    complexity = args.first;
  }

  // Add child complexity
  return complexity + childComplexity;
};

// Directive-based complexity
const schema = `
  directive @complexity(
    value: Int!
    multipliers: [String!]
  ) on FIELD_DEFINITION

  type Query {
    user(id: ID!): User @complexity(value: 1)
    users(limit: Int): [User!]! @complexity(
      value: 1,
      multipliers: ["limit"]
    )
    posts(first: Int): [Post!]! @complexity(
      value: 5,
      multipliers: ["first"]
    )
  }

  type User {
    id: ID!
    posts: [Post!]! @complexity(value: 10)
  }
`;

// Complexity validation plugin
const complexityPlugin = {
  requestDidStart: () => ({
    async didResolveOperation({ request, document, operationName }) {
      const complexity = calculateComplexity({
        document,
        operationName,
        variables: request.variables
      });

      const maxComplexity = 1000;

      if (complexity > maxComplexity) {
        throw new GraphQLError(
          `Query is too complex: ${complexity}. ` +
          `Maximum allowed: ${maxComplexity}`,
          {
            extensions: {
              code: 'QUERY_TOO_COMPLEX',
              complexity,
              maxComplexity
            }
          }
        );
      }
    }
  })
};

// Manual complexity calculation
const calculateComplexity = ({ document, operationName, variables }) => {
  let totalComplexity = 0;

  const visit = (node, multiplier = 1) => {
    if (node.kind === 'Field') {
      // Get field complexity from directive or default
      const complexity = getFieldComplexity(node);

      // Handle multipliers from arguments
      const args = getArguments(node, variables);
      const fieldMultiplier = getMultiplier(args);

      totalComplexity += complexity * multiplier * fieldMultiplier;

      // Visit child fields
      if (node.selectionSet) {
        node.selectionSet.selections.forEach(child =>
          visit(child, multiplier * fieldMultiplier)
        );
      }
    }
  };

  visit(document);
  return totalComplexity;
};

Depth Limiting

Prevent deeply nested queries that can cause performance issues and potential denial of service attacks.

import { ValidationContext, GraphQLError } from 'graphql';

const depthLimit = (maxDepth: number) => {
  return (validationContext: ValidationContext) => {
    return {
      Field(node, key, parent, path, ancestors) {
        const depth = ancestors.filter(
          ancestor => ancestor.kind === 'Field'
        ).length;

        if (depth > maxDepth) {
          validationContext.reportError(
            new GraphQLError(
              `Query exceeds maximum depth of ${maxDepth}. ` +
              `Found depth of ${depth}.`,
              {
                nodes: [node],
                extensions: {
                  code: 'DEPTH_LIMIT_EXCEEDED',
                  depth,
                  maxDepth
                }
              }
            )
          );
        }
      }
    };
  };
};

// Usage with Apollo Server
const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(7)]
});

// Example queries
// ✅ Allowed (depth: 4)
query {
  user {
    posts {
      comments {
        author {
          username
        }
      }
    }
  }
}

// ❌ Rejected (depth: 8)
query {
  user {
    friends {
      friends {
        friends {
          friends {
            friends {
              friends {
                friends {
                  username
                }
              }
            }
          }
        }
      }
    }
  }
}

Query Cost Analysis

Implement cost-based rate limiting to protect against expensive queries.

interface CostConfig {
  objectCost: number;
  scalarCost: number;
  defaultListSize: number;
}

const calculateQueryCost = (
  document,
  variables,
  config: CostConfig
) => {
  let totalCost = 0;

  const visit = (node, multiplier = 1) => {
    if (node.kind === 'Field') {
      const fieldType = getFieldType(node);

      // List cost
      if (isListType(fieldType)) {
        const listSize = getListSize(node, variables) ||
          config.defaultListSize;
        multiplier *= lis
Полный SKILL.md на GitHub

Установить graphql-performance в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл graphql-performance?

Use when optimizing GraphQL API performance with query complexity analysis, batching, caching strategies, depth limiting, monitoring, and database optimization.

Как установить скилл graphql-performance?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл graphql-performance запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить graphql-performance с