graphql-performance
БесплатноБез исполняемых скриптовНе проверенUse when optimizing GraphQL API performance with query complexity analysis, batching, caching strategies, depth limiting, monitoring, and database optimization.
от 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
Установить 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), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic