Design and implement GraphQL schemas, resolvers, and DataLoaders. Covers schema-first SDL, N+1 prevention, Relay pagination, and GraphQL vs REST decision criteria.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
| Critère | GraphQL | REST |
|---|---|---|
| Clients multiples (mobile/web/tiers) avec besoins différents | ✅ | ❌ sur-fetch |
| API publique stable et versionnée | ❌ complexe | ✅ |
| Upload de fichiers binaires | ❌ multipart lourd | ✅ |
| CRUD simple sans nested data | ❌ overhead | ✅ |
| Real-time natif (subscriptions) | ✅ | ❌ SSE/WS manuel |
Règle d'or : si un seul client consomme l'API et que les endpoints sont stables, REST suffit. GraphQL brille dès que plusieurs surfaces (mobile, web, partenaires) ont des besoins de champs divergents.
Définir le contrat avant le code. Partir du SDL, pas des modèles DB.
# types de base
type User {
id: ID!
email: String!
role: UserRole!
posts(first: Int = 10, after: String): PostConnection!
}
enum UserRole { ADMIN MEMBER GUEST }
# erreurs métier explicites — pas d'exceptions génériques
union CreateUserResult = User | EmailAlreadyExistsError | ValidationError
type EmailAlreadyExistsError { message: String! email: String! }
type ValidationError { message: String! field: String! }
type Mutation {
createUser(input: CreateUserInput!): CreateUserResult!
}
input CreateUserInput {
email: String!
password: String!
role: UserRole! = MEMBER
}
Check-list schéma
! uniquement ce qui est garantiinput types pour toutes les mutations (jamais des scalaires inline)"""description""") sur chaque type exposé@deprecated(reason: "…") plutôt qu'un v2Chaque résolveur de relation doit passer par un DataLoader. Sans ça, 100 posts = 100 requêtes DB.
// Apollo Server / TypeScript
import DataLoader from 'dataloader';
// Créer dans le contexte par requête (jamais en singleton global)
export function createLoaders(db: Db) {
return {
userById: new DataLoader<string, User>(async (ids) => {
const users = await db.users.findMany({ where: { id: { in: [...ids] } } });
const map = new Map(users.map(u => [u.id, u]));
return ids.map(id => map.get(id) ?? new Error(`User ${id} not found`));
}),
};
}
// Résolveur
const resolvers = {
Post: {
author: (post, _args, ctx) => ctx.loaders.userById.load(post.authorId),
},
};
Règle : le DataLoader doit respecter l'ordre et la taille du tableau d'entrée — renvoyer exactement ids.length éléments dans le même ordre.
Standard cursor-based, compatible avec tous les clients GraphQL.
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type PostEdge { node: Post! cursor: String! }
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
// Utilitaire cursor (base64 de l'ID ou d'un offset)
const encodeCursor = (id: string) => Buffer.from(id).toString('base64');
const decodeCursor = (cursor: string) => Buffer.from(cursor, 'base64').toString();
Ne pas mélanger offset (skip/limit) et cursor dans la même connexion — choisir un seul pattern par type.
Niveau contexte : injecter le user une seule fois.
// Apollo Server v4
const server = new ApolloServer({ typeDefs, resolvers });
const handler = startStandaloneServer(server, {
context: async ({ req }) => ({
user: await verifyJwt(req.headers.authorization),
loaders: createLoaders(db),
}),
});
Niveau champ — directive @auth avec graphql-shield (Node.js) ou attribute [Authorize] (Hot Chocolate .NET) :
// graphql-shield
import { shield, rule, and } from 'graphql-shield';
const isAuthenticated = rule()((_, __, ctx) => ctx.user != null);
const isAdmin = rule()((_, __, ctx) => ctx.user?.role === 'ADMIN');
export const permissions = shield({
Mutation: { deleteUser: and(isAuthenticated, isAdmin) },
});
Ne jamais filtrer des données sensibles uniquement côté client — le résolveur doit refuser, pas cacher.
| Type d'erreur | Approche |
|---|---|
| Erreur métier prévisible | Union type dans le schéma (CreateUserResult) |
| Erreur d'autorisation | GraphQLError avec extensions.code: 'FORBIDDEN' |
| Erreur technique (500) | Masquer le détail en prod, logger côté serveur |
import { GraphQLError } from 'graphql';
// Erreur d'autorisation
throw new GraphQLError('Access denied', {
extensions: { code: 'FORBIDDEN', http: { status: 403 } },
});
Protocole recommandé 2026 : graphql-ws (supercède subscriptions-transport-ws déprécié).
// Apollo Server + graphql-ws + Redis Pub/Sub
import { RedisPubSub } from 'graphql-redis-subscriptions';
const pubsub = new RedisPubSub({ connection: process.env.REDIS_URL });
const resolvers = {
Subscription: {
messageAdded: {
subscribe: (_root, { channelId }, ctx) => {
if (!ctx.user) throw new GraphQLError('Unauthenticated');
return pubsub.asyncIterableIterator(`CHANNEL_${channelId}`);
},
},
},
Mutation: {
sendMessage: async (_root, { input }, ctx) => {
const msg = await db.messages.create({ data: input });
await pubsub.publish(`CHANNEL_${input.channelId}`, { messageAdded: msg });
return msg;
},
},
};
Multi-instance : toujours utiliser un bus externe (Redis) — un EventEmitter in-memory ne fonctionne que sur une seule instance.
Utiliser Apollo Federation v2 quand plusieurs équipes ownt des domaines distincts.
# Sous-graphe "users"
type User @key(fields: "id") {
id: ID!
email: String!
}
# Sous-graphe "posts" — étend l'entité User
type User @key(fields: "id") @extends {
id: ID! @external
posts: [Post!]!
}
Coût opérationnel : gateway supplémentaire, schema registry, composition à valider en CI. Ne pas fédérer un monolithe si l'équipe est < 5 devs.
// Depth limiting + complexity scoring (Apollo Server)
import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';
const server = new ApolloServer({
typeDefs, resolvers,
validationRules: [
depthLimit(7),
createComplexityLimitRule(1000),
],
});
Persisted queries (Apollo) : le client envoie un hash SHA-256, le serveur valide contre une allowlist. Bloque les requêtes arbitraires en prod.
# Générer le manifest avec Rover CLI
rover graph introspect http://localhost:4000 > schema.graphql
rover persisted-queries publish --graph-id MY_GRAPH --manifest manifest.json
| Piège | Solution |
|---|---|
| Résolveurs sans DataLoader → N+1 | DataLoader systématique sur toutes les relations |
| Nullable partout par confort | Réfléchir explicitement à chaque ! |
| Exposer l'erreur DB brute en prod | Masquer, logger, renvoyer un code générique |
| Mutations sans input type | Toujours un XxxInput — facilite les évolutions |
| Federation prématurée | Schéma monolithique d'abord, fedérer quand la friction inter-équipes est réelle |
any en TypeScript dans les résolveurs | Utiliser graphql-codegen pour typer automatiquement |
| Subscriptions sur un EventEmitter in-memory | Redis Pub/Sub ou NATS pour multi-instance |
| Pas de rate limiting sur les queries | Complexity scoring + IP rate-limit sur le endpoint |
| Besoin | Outil |
|---|---|
| Codegen types TS depuis SDL | @graphql-codegen/cli |
| Linter schéma | @graphql-inspector/cli |
| Test résolveurs | graphql-tester, Jest + @apollo/server-integration-testing |
| Exploration API | GraphiQL, Apollo Sandbox, Insomnia |
| .NET | Hot Chocolate 14+ (source generators, AOT) |
| Python | Strawberry (type-first, async natif) |
| Monitoring | Apollo Studio, Stellate (edge caching) |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests"./agent-autogen-guideDéveloppement d'agents conversationnels avec Microsoft AutoGen. Création de group chats, agents spécialisés et workflows multi-agents avec exécution de code. Se déclenche avec "AutoGen", "Microsoft AutoGen", "autogen agent", "group chat agent", "ConversableAgent", "AssistantAgent", "UserProxyAgent", "coding agent", "agents qui conversent". Also triggers on "AutoGen agents", "group chat agents", "conversable agent"./agent-browser-agent-builderConstruction d'agents de navigation web autonomes incluant scraping intelligent, interaction DOM et gestion de sessions. Se déclenche avec "browser agent", "agent navigateur", "agent web autonome", "Puppeteer agent", "Playwright agent. Also triggers on "web browsing agent", "autonomous scraping agent"./agent-claude-code-extension-builderConstruction d'extensions et skills pour Claude Code — slash commands, hooks, intégration MCP et commandes personnalisées. Se déclenche avec "extension Claude Code", "skill Claude", "slash command", "Claude Code plugin", "custom command Claude". Also triggers on "build a Claude Code plugin", "custom slash command", "Claude Code hooks"./claude-skills-collection:dev-graphql-builderfrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collectionOther plugins' skills for the same job