Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问许可证需确认审计通过

graphqlGraphQL 接口开发

Agent Skill

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

总安装

512

周安装

22

GitHub Stars

12

下载量

180
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:graphql(GraphQL 接口开发)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/graphql
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill graphql
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill graphql

简介

用于 API 契约设计与查询语言开发,替代传统 REST 接口。

  • 支持嵌套字段加载、分页游标与订阅实时更新。
  • 提供类型安全校验与持久层映射实现指导。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。
  • 复杂查询应添加深度限制,防止 N+1 问题拖垮性能。
  • graphql 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

GraphQL Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: graphql for comprehensive documentation.

Schema Definition

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  createdAt: DateTime!
}

type Post {
  id: ID!
  title: String!
  content: String
  author: User!
  published: Boolean!
}

type Query {
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
  post(id: ID!): Post
}

type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}

input CreateUserInput {
  name: String!
  email: String!
}

Resolvers

const resolvers = {
  Query: {
    user: (_, { id }, context) => {
      return context.db.users.findUnique({ where: { id } });
    },
    users: (_, { limit, offset }, context) => {
      return context.db.users.findMany({ take: limit, skip: offset });
    },
  },
  Mutation: {
    createUser: (_, { input }, context) => {
      return context.db.users.create({ data: input });
    },
  },
  User: {
    posts: (parent, _, context) => {
      return context.db.posts.findMany({ where: { authorId: parent.id } });
    },
  },
};

Queries

query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
    posts {
      title
      published
    }
  }
}

mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) {
    id
    name
  }
}

When NOT to Use This Skill

  • REST API design (use rest-api skill)
  • OpenAPI/Swagger documentation (use openapi skill)
  • tRPC type-safe APIs (use trpc skill)
  • Generating GraphQL types from schema (use graphql-codegen skill)
  • Simple CRUD operations where REST is sufficient

Best Practices

DoDon't
Use input types for mutationsN+1 queries (use DataLoader)
Implement paginationReturn unbounded lists
Add field-level authExpose sensitive data
Use fragments for reuseOver-fetch data

Anti-Patterns

Anti-PatternWhy It's BadSolution
N+1 queriesCauses performance issues, database overloadUse DataLoader for batching
Exposing implementation details in schemaTight coupling, hard to refactorUse domain-driven schema design
No pagination on listsMemory issues, slow responsesImplement cursor or offset pagination
Allowing unbounded query depthDoS vulnerabilityAdd depth limiting
No query complexity limitsResource exhaustionAdd complexity analysis
Exposing sensitive fields without authSecurity vulnerabilityAdd field-level authorization
Using String for IDsType safety issuesUse ID! scalar type
Returning null instead of errorsPoor error handlingUse proper GraphQL error responses

Quick Troubleshooting

IssuePossible CauseSolution
Slow query performanceN+1 queriesImplement DataLoader, check resolver patterns
High memory usageLarge unbounded listsAdd pagination, limit query depth
"Cannot return null for non-nullable field"Missing data or resolver errorCheck database queries, add error handling
Query rejectedDepth or complexity limit exceededOptimize query, reduce nesting
Authentication errorsMissing or invalid tokenCheck context creation, verify token
Type mismatch errorsSchema/resolver mismatchEnsure resolver return types match schema
CORS errorsServer configuration issueConfigure CORS in Apollo Server
Introspection disabledProduction security settingEnable for development, disable in production

Production Readiness

Security Configuration

// Query depth limiting
import depthLimit from 'graphql-depth-limit';

const server = new ApolloServer({
  schema,
  validationRules: [depthLimit(10)], // Max 10 levels deep
});

// Query complexity limiting
import { createComplexityLimitRule } from 'graphql-validation-complexity';

const complexityLimitRule = createComplexityLimitRule(1000, {
  scalarCost: 1,
  objectCost: 10,
  listFactor: 10,
});

// Disable introspection in production
const server = new ApolloServer({
  introspection: process.env.NODE_ENV !== 'production',
  plugins: [
    process.env.NODE_ENV === 'production'
      ? ApolloServerPluginLandingPageDisabled()
      : ApolloServerPluginLandingPageLocalDefault(),
  ],
});

N+1 Query Prevention (DataLoader)

import DataLoader from 'dataloader';

// Create loader per request (in context)
function createLoaders(db: PrismaClient) {
  return {
    userLoader: new DataLoader<string, User>(async (ids) => {
      const users = await db.user.findMany({
        where: { id: { in: [...ids] } },
      });
      const userMap = new Map(users.map(u => [u.id, u]));
      return ids.map(id => userMap.get(id) || null);
    }),

    postsByUserLoader: new DataLoader<string, Post[]>(async (userIds) => {
      const posts = await db.post.findMany({
        where: { authorId: { in: [...userIds] } },
      });
      const postsByUser = new Map<string, Post[]>();
      posts.forEach(p => {
        const existing = postsByUser.get(p.authorId) || [];
        postsByUser.set(p.authorId, [...existing, p]);
      });
      return userIds.map(id => postsByUser.get(id) || []);
    }),
  };
}

// Use in resolvers
const resolvers = {
  User: {
    posts: (parent, _, context) => {
      return context.loaders.postsByUserLoader.load(parent.id);
    },
  },
};

Field-Level Authorization

import { rule, shield, and, or } from 'graphql-shield';

const isAuthenticated = rule()((parent, args, context) => {
  return context.user !== null;
});

const isAdmin = rule()((parent, args, context) => {
  return context.user?.role === 'ADMIN';
});

const isOwner = rule()((parent, args, context) => {
  return parent.authorId === context.user?.id;
});

const permissions = shield({
  Query: {
    users: isAuthenticated,
    user: isAuthenticated,
  },
  Mutation: {
    deleteUser: and(isAuthenticated, or(isAdmin, isOwner)),
    updateUser: and(isAuthenticated, or(isAdmin, isOwner)),
  },
  User: {
    email: or(isAdmin, isOwner), // Only owner or admin can see email
  },
});

const server = new ApolloServer({
  schema: applyMiddleware(schema, permissions),
});

Rate Limiting

import { rateLimitDirective } from 'graphql-rate-limit-directive';

const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } =
  rateLimitDirective();

const typeDefs = gql`
  ${rateLimitDirectiveTypeDefs}

  type Query {
    users: [User!]! @rateLimit(limit: 100, duration: 60)
  }

  type Mutation {
    createUser(input: CreateUserInput!): User!
      @rateLimit(limit: 10, duration: 60)
  }
`;

Error Handling

// Custom error formatting
const server = new ApolloServer({
  formatError: (formattedError, error) => {
    // Log original error
    logger.error(error);

    // Don't leak internal errors
    if (formattedError.extensions?.code === 'INTERNAL_SERVER_ERROR') {
      return {
        message: 'Internal server error',
        extensions: {
          code: 'INTERNAL_SERVER_ERROR',
        },
      };
    }

    // Remove stack trace in production
    if (process.env.NODE_ENV === 'production') {
      delete formattedError.extensions?.stacktrace;
    }

    return formattedError;
  },
});

Monitoring Metrics

MetricAlert Threshold
Query duration p99> 500ms
Error rate> 1%
Complexity score (avg)> 500
Depth exceeded errors> 10/min
DataLoader cache hit ratio< 50%

Pagination (Relay-style)

type Query {
  users(first: Int, after: String, last: Int, before: String): UserConnection!
}

type UserConnection {
  edges: [UserEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type UserEdge {
  cursor: String!
  node: User!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

Request Logging

const server = new ApolloServer({
  plugins: [
    {
      async requestDidStart(requestContext) {
        const start = Date.now();

        return {
          async willSendResponse(ctx) {
            logger.info({
              operationName: ctx.request.operationName,
              query: ctx.request.query,
              variables: ctx.request.variables,
              duration: Date.now() - start,
              errors: ctx.errors?.length || 0,
            });
          },
        };
      },
    },
  ],
});

Checklist

  • Query depth limiting
  • Query complexity limiting
  • Introspection disabled in production
  • DataLoader for N+1 prevention
  • Field-level authorization
  • Rate limiting on mutations
  • Custom error formatting
  • Relay-style pagination
  • Request logging with timing
  • Input validation
  • Persisted queries (optional)
  • APQ (Automatic Persisted Queries) enabled

Code Generation

GraphQL Codegen generates TypeScript types and hooks from your GraphQL schema and operations.

Quick Setup

npm install -D @graphql-codegen/cli @graphql-codegen/client-preset
// codegen.ts
import { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: ['src/**/*.graphql', 'src/**/*.tsx'],
  generates: {
    './src/gql/': {
      preset: 'client',
      plugins: [],
    },
  },
};

export default config;

Generated Usage

import { graphql } from '@/gql';
import { useQuery } from '@tanstack/react-query';

const UserQuery = graphql(`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`);

function UserProfile({ id }: { id: string }) {
  const { data } = useQuery({
    queryKey: ['user', id],
    queryFn: () => request(endpoint, UserQuery, { id }),
  });

  return <div>{data?.user?.name}</div>;
}

Related Skills

SkillPurpose
GraphQL CodegenFull codegen setup
TanStack QueryData fetching hooks
React APIAlternative data patterns

Reference Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.27%
按下载量换算62

Claude

30.54%
按下载量换算55

Cursor

19.37%
按下载量换算35

Gemini CLI

8.39%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills