К основному содержанию
скилл CX Codex

graphql-schema — скилл для Claude Code: что делает и как установить

Скилл обучает проектированию схем GraphQL SDL по практикам Apollo. Помогает при создании schema.graphql, добавлении мутаций или настройке пагинации.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add apollographql/skills --skill graphql-schema -a claude-code
Открыть на GitHub

Что делает graphql-schema

Скилл задаёт правила проектирования GraphQL SDL для файлов вроде schema.graphql и определений typeDefs. Он организует типы вокруг задач клиента, а не таблиц базы данных. Это сохраняет совместимость API.

Внутри собраны рекомендации по пагинации списков и обработке ошибок с соединениями Connection. Правила требуют использовать форму [Type!]! для списков, оформлять мутации через аргумент input и назначать ID для идентификаторов. Субагенту разрешены вызовы npm, npx, чтение и редактирование файлов.

Скилл прямо запрещает добавлять обязательные аргументы без значений по умолчанию. Иначе старые клиенты падают на валидации. Подход совместим с Apollo Server или Yoga.

Какие задачи решает

  • спроектировать типы и мутации в файле schema.graphql
  • перевести пагинацию списков на курсоры и соединения Connection
  • проверить схему на обратную совместимость перед релизом
  • настроить обязательность полей и списков через модификаторы !

Примеры запросов агенту

  • Спроектируй схему для оформления заказов в schema.graphql с пагинацией и мутациями
  • Проверь typeDefs на обратную совместимость и добавь описания полей
  • Добавь в схему тип User с пагинацией постов через PostConnection

Как установить graphql-schema

1Через Skills CLI (Vercel)

npx skills add apollographql/skills --skill graphql-schema -a claude-code

2Вручную: положить файлы

~/.claude/skills/graphql-schema/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/graphql-schema/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о graphql-schema

Как установить graphql-schema в Claude Code?

Выполните команду npx skills add apollographql/skills --skill graphql-schema -a claude-code.

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

Он инструктирует агента при написании GraphQL SDL, требуя использовать непустые списки [Type!]!, единый аргумент input для мутаций и курсорную пагинацию.

С какими серверами GraphQL совместим скилл?

Скилл подходит для любой реализации GraphQL, включая Apollo Server или Yoga.

Исходный текст

SKILL.md · MIT
---
name: graphql-schema
description: >
  Guide for designing and changing GraphQL schemas following industry best practices. Use this skill
  whenever you create or edit GraphQL SDL, such as a `schema.graphql` file or `typeDefs`, including when:
  (1) designing a new GraphQL schema or API,
  (2) adding or changing types, fields, arguments, mutations, or descriptions in an existing schema,
  (3) reviewing existing schema for improvements,
  (4) deciding on type structures or nullability,
  (5) implementing pagination or error patterns,
  (6) ensuring security in schema design.
license: MIT
compatibility: Any GraphQL implementation (Apollo Server, graphql-js, Yoga, etc.)
metadata:
  author: apollographql
  version: "1.0.2"
allowed-tools: Bash(npm:*) Bash(npx:*) Read Write Edit Glob Grep
---

# GraphQL Schema Design Guide

This guide covers best practices for designing GraphQL schemas that are intuitive, performant, and maintainable. Schema design is primarily a server-side concern that directly impacts API usability.

## Schema Design Principles

### 1. Design for Client Needs

- Think about what queries clients will write
- Organize types around use cases, not database tables
- Expose capabilities, not implementation details

### 2. Be Explicit

- Use clear, descriptive names
- Make nullability intentional
- Document with descriptions

### 3. Design for Evolution

- Plan for backwards compatibility
- Use deprecation before removal
- Avoid breaking changes
- Give every new argument or input field a default value, or make it nullable. Existing clients don't send it, so a required field without a default makes their requests fail validation.

## Quick Reference

### Type Definition Syntax

```graphql
"""
A user in the system.
"""
type User {
  id: ID!
  email: String!
  name: String
  posts(first: Int = 10, after: String): PostConnection!
  createdAt: DateTime!
}
```

### Nullability Rules

| Pattern | Meaning |
|---------|---------|
| String | Nullable - may be null |
| String! | Non-null - always has value |
| [String] | Nullable list, nullable items |
| [String!] | Nullable list, non-null items |
| [String]! | Non-null list, nullable items |
| [String!]! | Non-null list, non-null items |

**Best Practice:** Use **[Type!]!** for lists - empty list over null, no null items.

### Input vs Output Types

```graphql
# Output type - what clients receive
type User {
  id: ID!
  email: String!
  createdAt: DateTime!
}

# Input type - what clients send
input CreateUserInput {
  email: String!
  name: String
}

# Mutation using input type
type Mutation {
  createUser(input: CreateUserInput!): User!
}
```

### Interface Pattern

```graphql
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  email: String!
}

type Post implements Node {
  id: ID!
  title: String!
}
```

### Union Pattern

```graphql
union SearchResult = User | Post | Comment

type Query {
  search(query: String!): [SearchResult!]!
}
```

## Reference Files

Detailed documentation for specific topics:

- [Types](references/types.md) - Type design patterns, interfaces, unions, and custom scalars
- [Naming](references/naming.md) - Naming conventions for types, fields, and arguments
- [Pagination](references/pagination.md) - Connection pattern and cursor-based pagination
- [Errors](references/errors.md) - Error modeling and result types
- [Security](references/security.md) - Security best practices for schema design

## Key Rules

### Type Design

- Define types based on domain concepts, not data storage
- Use interfaces for shared fields across types
- Use unions for mutually exclusive types
- Keep types focused (single responsibility)
- Avoid deep nesting - flatten when possible

### Field Design

- Fields should be named from client's perspective
- Return the most specific type possible
- Make expensive fields explicit (consider arguments)
- Use arguments for filtering, sorting, pagination

### Mutation Design

- Use single input argument pattern: `mutation(input: InputType!)`
- Return affected objects in mutation responses
- Model mutations around business operations, not CRUD
- Consider returning a union of success/error types

### ID Strategy

- Use globally unique IDs when possible
- Implement `Node` interface for refetchability
- Base64-encode compound IDs if needed

## Ground Rules

- ALWAYS add descriptions to types and fields
- ALWAYS use non-null (**!**) for fields that cannot be null
- ALWAYS use **[Type!]!** pattern for lists
- ALWAYS paginate lists that can grow without limit, such as `Query.users` or `Post.comments`: return a connection and give `first` a default page size
- NEVER expose database internals in schema
- NEVER break backwards compatibility without deprecation
- NEVER add a required argument or input field without a default value
- PREFER dedicated input types over many arguments
- PREFER enums over arbitrary strings for fixed values
- USE `ID` type for identifiers, not `String` or `Int`
- USE custom scalars for domain-specific values (DateTime, Email, URL)

© apollographql · MIT · apollographql/skills

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

Всё по теме «Бэкенд и API» →
graphql-implementation secondsky Скилл для сборки GraphQL API: схема, резолверы, обработка ошибок и защита от N+1. Пригодится при переходе с REST и при подписках в реальном времени. CX Codex +1 380установок neo4j-graphql-skill neo4j-contrib Скилл помогает собрать GraphQL API на @neo4j/graphql: типы, директивы, авторизация через JWT и подключение к Apollo Server. CX Codex +1 809установок apollo-graphql Mindrally Скилл задаёт агенту правила работы с Apollo Client: запросы, мутации, фрагменты, кэш и оптимистичные обновления в React-проектах на GraphQL. CX Codex +1 677установок graphql-development Mindrally Набор правил для GraphQL: схема, типизированные клиенты, интеграция с React и Next.js. Пригодится, когда агент пишет резолверы и запросы. CX Codex +1 661установок graphql-performance-optimizer davila7 Субагент разбирает медленные GraphQL-запросы: находит N+1, ставит DataLoader, настраивает кеширование. Пригодится, когда список пользователей грузится секундами. 599установок graphql-and-hidden-parameters yaklang Плейбук по тестированию GraphQL и скрытых параметров: интроспекция, батчинг, недокументированные поля и дыры в авторизации. CX Codex +1 3 600установок

Из того же набора11

rust-best-practices Скилл для написания и ревью Rust-кода по хендбуку Apollo GraphQL: заимствование против клонирования, обработка ошибок, тесты. CX Codex +1 21 100установок apollo-client Скилл ведёт агента по настройке Apollo Client 4.x в React: запросы, мутации, кэш, локальное состояние и разбор ошибок. CX Codex +1 5 600установок graphql-operations Скилл для написания GraphQL-операций: запросы, мутации, подписки и фрагменты по правилам проекта. Пригодится, когда агент сочиняет операции наугад. CX Codex +1 3 600установок apollo-server Помогает проектировать GraphQL-серверы на базе Apollo Server 5.x. Пригодится при настройке схемы, типизации резолверов и авторизации в Node.js. CX Codex +1 2 800установок apollo-connectors Помогает подключить REST API к GraphQL-суперграфу через директивы @source и @connect. Годится для быстрых правок уже существующей схемы Connectors. CX Codex +1 2 200установок apollo-federation Помогает писать схемы подграфов Apollo Federation: директивы, сущности с @key, ошибки композиции. Полезен, когда суперграф собирается из нескольких GraphQL-сервисов. CX Codex +1 1 900установок apollo-router Скилл генерирует корректный router.yaml для Apollo Router v1.x и v2.x и подсказывает, какие секции в этих версиях несовместимы. CX Codex +1 1 800установок apollo-kotlin Скилл ведёт агента по настройке Apollo Kotlin в Gradle-проекте: схема, кодогенерация, ApolloClient с авторизацией и кэшем, запросы и подписки. CX Codex +1 1 700установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой