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

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

Помогает проектировать GraphQL-серверы на базе Apollo Server 5.x. Пригодится при настройке схемы, типизации резолверов и авторизации в Node.js.

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

Что делает apollo-server

Скилл даёт модели инструкции по работе с Apollo Server 5.x без устаревших подходов четвёртой версии. Он описывает объявление схем и скаляров, генерацию резолверов с сигнатурой (parent, args, contextValue, info), подключение контекста для авторизации и интеграцию источников данных вроде RESTDataSource или DataLoader.

Внутри заложены шаблоны для автономного режима startStandaloneServer и связки с Express через @as-integrations/express5. Скилл прямо советует standalone только для прототипов, требуя переходить на Express или Fastify в продакшене. Ошибки принудительно форматируются через GraphQLError из пакета graphql.

Для работы требуются Node.js v20+ и TypeScript 4.7+. Если проект ещё на старых версиях Node.js или использует API Apollo Server v4, предложенный код вызовет ошибки сборки из-за несовместимости типов и методов middleware.

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

  • развернуть GraphQL-сервер на базе Apollo Server 5.x
  • написать типизированные схемы и резолверы для запросов и мутаций
  • настроить авторизацию через контекст запроса в Express или standalone-режиме
  • устранить проблему N+1 в запросах с помощью DataLoader

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

  • Создай базовый сервер Apollo Server 5 на Express с авторизацией по Bearer-токену
  • Напиши схему GraphQL и резолверы для сущностей User и Post
  • Добавь DataLoader для устранения проблемы N+1 при выборке постов автора

Как установить apollo-server

1Через Skills CLI (Vercel)

npx skills add apollographql/skills --skill apollo-server -a claude-code

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

~/.claude/skills/apollo-server/SKILL.md

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

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

Из того же набора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-schema Скилл обучает проектированию схем GraphQL SDL по практикам Apollo. Помогает при создании schema.graphql, добавлении мутаций или настройке пагинации. CX Codex +1 4 000установок graphql-operations Скилл для написания GraphQL-операций: запросы, мутации, подписки и фрагменты по правилам проекта. Пригодится, когда агент сочиняет операции наугад. CX Codex +1 3 600установок 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установок

Похожие

apollo-graphql Mindrally Скилл задаёт агенту правила работы с Apollo Client: запросы, мутации, фрагменты, кэш и оптимистичные обновления в React-проектах на GraphQL. CX Codex +1 677установок graphql-architect https://github.com/Jeffallan Помогает проектировать схемы GraphQL, настраивать подграфы Apollo Federation 2.5+ и устранять проблему N+1 с помощью DataLoader. CX Codex +1 4 000установок nodejs-backend-patterns Seth Hobson Подсказывает агенту, как строить серверы на Express и Fastify: middleware, обработка ошибок, авторизация, работа с базами. CX Codex 48 535установок express-typescript Mindrally Правила для агента, который пишет API на Express.js и TypeScript: структура проекта, middleware, валидация и безопасность. CX Codex +1 1 400установок backend-patterns affaan-m Скилл с паттернами бэкенда для Node.js, Express и Next.js API routes: слои, кэш, транзакции, обработка ошибок. CX Codex +1 6 000установок prototype-pollution yaklang Проверяет JavaScript-код на prototype pollution: от опасных merge-операций до чтения загрязнённых свойств. Нужен для авторизованных аудитов Node и браузерных приложений. CX Codex +1 3 600установок

Рядом в теме «Бэкенд и API»

Всё по теме «Бэкенд и API» →

Вопросы о apollo-server

Как установить apollo-server в Claude Code?

Выполните команду npx skills add apollographql/skills --skill apollo-server -a claude-code. Скилл сразу добавится в окружение агента.

Что делает скилл apollo-server?

Он направляет агента при проектировании GraphQL API на Apollo Server 5.x. Правила задают типизацию контекста, структуру схем и корректную обработку ошибок.

Какие версии Node.js и TypeScript нужны для работы?

Скилл рассчитан на Node.js v20+ и TypeScript 4.7+. Он поддерживает автономный запуск, Express v4/v5, Fastify и бессерверные среды.

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

SKILL.md · MIT
---
name: apollo-server
description: >
  Guide for building GraphQL servers with Apollo Server 5.x. Use this skill when:
  (1) setting up a new Apollo Server project,
  (2) writing resolvers or defining GraphQL schemas,
  (3) implementing authentication or authorization,
  (4) creating plugins or custom data sources,
  (5) troubleshooting Apollo Server errors or performance issues.
license: MIT
compatibility: Node.js v20+, TypeScript 4.7+. Works with Express v4/v5, standalone, Fastify, and serverless.
metadata:
  author: apollographql
  version: "1.0.0"
allowed-tools: Bash(npm:*) Bash(npx:*) Bash(node:*) Read Write Edit Glob Grep
---

# Apollo Server 5.x Guide

Apollo Server is an open-source GraphQL server that works with any GraphQL schema. Apollo Server 5 is framework-agnostic and runs standalone or integrates with Express, Fastify, and serverless environments.

## Quick Start

### Step 1: Install

```bash
npm install @apollo/server graphql
```

For Express integration:

```bash
npm install @apollo/server @as-integrations/express5 express graphql cors
```

### Step 2: Define Schema

```typescript
const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;
```

### Step 3: Write Resolvers

```typescript
const resolvers = {
  Query: {
    books: () => [
      { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
      { title: "1984", author: "George Orwell" },
    ],
  },
};
```

### Step 4: Start Server

**Standalone (Recommended for prototyping):**

The standalone server is great for prototyping, but for production services, we recommend integrating Apollo Server with a more fully-featured web framework such as Express, Koa, or Fastify. Swapping from the standalone server to a web framework later is straightforward.

```typescript
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const server = new ApolloServer({ typeDefs, resolvers });

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
});

console.log(`Server ready at ${url}`);
```

**Express:**

```typescript
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import express from "express";
import http from "http";
import cors from "cors";

const app = express();
const httpServer = http.createServer(app);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  "/graphql",
  cors(),
  express.json(),
  expressMiddleware(server, {
    context: async ({ req }) => ({ token: req.headers.authorization }),
  }),
);

await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log("Server ready at http://localhost:4000/graphql");
```

## Schema Definition

### Scalar Types

- `Int` - 32-bit integer
- `Float` - Double-precision floating-point
- `String` - UTF-8 string
- `Boolean` - true/false
- `ID` - Unique identifier (serialized as String)

### Type Definitions

```graphql
type User {
  id: ID!
  name: String!
  email: String
  posts: [Post!]!
}

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

input CreatePostInput {
  title: String!
  content: String
}

type Query {
  user(id: ID!): User
  users: [User!]!
}

type Mutation {
  createPost(input: CreatePostInput!): Post!
}
```

### Enums and Interfaces

```graphql
enum Status {
  DRAFT
  PUBLISHED
  ARCHIVED
}

interface Node {
  id: ID!
}

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

## Resolvers Overview

Resolvers follow the signature: `(parent, args, contextValue, info)`

- **parent**: Result from parent resolver (root resolvers receive undefined)
- **args**: Arguments passed to the field
- **contextValue**: Shared context object (auth, dataSources, etc.)
- **info**: Field-specific info and schema details (rarely used)

```typescript
const resolvers = {
  Query: {
    user: async (_, { id }, { dataSources }) => {
      return dataSources.usersAPI.getUser(id);
    },
  },
  User: {
    posts: async (parent, _, { dataSources }) => {
      return dataSources.postsAPI.getPostsByAuthor(parent.id);
    },
  },
  Mutation: {
    createPost: async (_, { input }, { dataSources, user }) => {
      if (!user) throw new GraphQLError("Not authenticated");
      return dataSources.postsAPI.create({ ...input, authorId: user.id });
    },
  },
};
```

## Context Setup

Context is created per-request and passed to all resolvers.

```typescript
interface MyContext {
  token?: string;
  user?: User;
  dataSources: {
    usersAPI: UsersDataSource;
    postsAPI: PostsDataSource;
  };
}

const server = new ApolloServer<MyContext>({
  typeDefs,
  resolvers,
});

// Standalone
const { url } = await startStandaloneServer(server, {
  context: async ({ req }) => ({
    token: req.headers.authorization || "",
    user: await getUser(req.headers.authorization || ""),
    dataSources: {
      usersAPI: new UsersDataSource(),
      postsAPI: new PostsDataSource(),
    },
  }),
});

// Express middleware
expressMiddleware(server, {
  context: async ({ req, res }) => ({
    token: req.headers.authorization,
    user: await getUser(req.headers.authorization),
    dataSources: {
      usersAPI: new UsersDataSource(),
      postsAPI: new PostsDataSource(),
    },
  }),
});
```

## Reference Files

Detailed documentation for specific topics:

- [Resolvers](references/resolvers.md) - Resolver patterns and best practices
- [Context and Auth](references/context-and-auth.md) - Authentication and authorization
- [Plugins](references/plugins.md) - Server and request lifecycle hooks
- [Data Sources](references/data-sources.md) - RESTDataSource and DataLoader
- [Error Handling](references/error-handling.md) - GraphQLError and error formatting
- [Troubleshooting](references/troubleshooting.md) - Common issues and solutions

## Key Rules

### Schema Design

- Use **!** (non-null) for fields that always have values
- Prefer input types for mutations over inline arguments
- Use interfaces for polymorphic types
- Keep schema descriptions for documentation

### Resolver Best Practices

- Keep resolvers thin - delegate to services/data sources
- Always handle errors explicitly
- Use DataLoader for batching related queries
- Return partial data when possible (GraphQL's strength)

### Performance

- Use `@defer` and `@stream` for large responses
- Implement DataLoader to solve N+1 queries
- Consider persisted queries for production
- Use caching headers and CDN where appropriate

## Ground Rules

- ALWAYS use Apollo Server 5.x patterns (not v4 or earlier)
- ALWAYS type your context with TypeScript generics
- ALWAYS use `GraphQLError` from `graphql` package for errors
- NEVER expose stack traces in production errors
- PREFER `startStandaloneServer` for prototyping only
- USE an integration with a server framework like Express, Koa, Fastify, Next, etc. for production apps
- IMPLEMENT authentication in context, authorization in resolvers

© apollographql · MIT · apollographql/skills

Смотрите также

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

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