apollo-server

tarafından apollographql

Apollo Server 5.x ile çeşitli framework'lerde GraphQL sunucuları oluşturmak için kapsamlı rehber. Şema tanımı, çözücüler, bağlam kurulumu ve TypeScript desteğiyle hata yönetimini kapsar. Prototipleme için bağımsız modu ve Express, Fastify, Koa ile sunucusuz ortamlar için entegrasyonları destekler. Çözücü desenleri, kimlik doğrulama/yetkilendirme, eklentiler, N+1 önleme için DataLoader ve performans optimizasyon tekniklerini içerir. Veri kaynakları, hata... için referans dokümantasyon sağlar.

npx skills add https://github.com/apollographql/skills --skill apollo-server

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

npm install @apollo/server graphql

For Express integration:

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

Step 2: Define Schema

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

  type Query {
    books: [Book]
  }
`;

Step 3: Write Resolvers

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.

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:

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

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

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)
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.

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:

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 tarafından daha fazla skill

apollo-client
apollographql
Apollo Client, JavaScript için kapsamlı bir durum yönetimi kütüphanesidir ve GraphQL ile hem yerel hem de uzak verileri yönetmenizi sağlar. 4.x sürümü, geliştirilmiş önbellekleme, daha iyi TypeScript desteği ve React 19 uyumluluğu sunar.
official
apollo-client
apollographql
We need to translate the given text from English to Turkish, preserving the name "apollo-client" and any technical terms like "queries", "mutations", "caching", "state management", "React", "Apollo Client 4.x", "Vite", "CRA", "Next.js App Router", "React Server Components", "React Router 7", "streaming SSR", "TanStack Start", "useQuery", "useLazyQuery", "useMutation", "useSuspenseQuery", "useBackgroundQuery", "Suspense", "React 18+", "19". Also preserve URLs if any (none here). Do not add any extra commentary or labels. Just output the translated text. The text: "Comprehensive guide for building React applications with Apollo Client 4.x, covering queries, mutations, caching, and state management. Supports multiple React frameworks and setups: client-side apps (Vite, CRA), Next.js App Router with React Server Components, React Router 7 with streaming SSR, and TanStack Start Includes hooks
official
apollo-connectors
apollographql
REST API'lerini @source ve @connect yönergelerini kullanarak GraphQL süper grafiklerine entegre eder. Yapılandırılmış 5 adımlı bir süreç sunar: API yapısını araştırma, yönergelerle şema uygulama, rover supergraph compose ile doğrulama, bağlayıcıları çalıştırma ve test kapsamı. Başlıklar, gövde yükleri, N+1 desenleri için toplu işleme ve $env aracılığıyla ortam değişkeni enjeksiyonu dahil olmak üzere istek yapılandırmasını destekler. Alan seçimi, takma adlandırma, iç içe veriler için alt seçimler ve varlık... ile yanıt eşlemesini yönetir.
official
apollo-federation
apollographql
Apollo Federation, birden fazla GraphQL API'sini (alt grafikler) birleşik bir süper grafik halinde oluşturmayı sağlar.
official
apollo-ios
apollographql
We need to translate the given English text into Turkish, preserving the name "apollo-ios" and technical terms like GraphQL, Swift, async/await, SQLite, HTTP, WebSocket, graphql-transport-ws. The instruction says to translate only the text inside <text>, and not include the name unless it appears in the source text. The name "apollo-ios" does not appear in the source text; the source says "Apollo iOS" (with a space). The instruction says "Name to preserve: apollo-ios" but the source has "Apollo iOS". We should preserve the exact name as given? The instruction says "preserve product names" and the name to preserve is "apollo-ios". However, the source text uses "Apollo iOS". I think we should keep "Apollo iOS" as is because that's the product name in the source. But the instruction says "Name to preserve: apollo-ios" - that might be a key. To be safe, I'll keep "Apollo iOS
official
apollo-kotlin
apollographql
Apollo Kotlin, GraphQL işlemlerinizden ve şemanızdan Kotlin modelleri oluşturan, Android, JVM ve Kotlin Multiplatform projelerinde kullanılabilen, güçlü türde bir GraphQL istemcisidir.
official
apollo-mcp-server
apollographql
AI ajanlarını, Model Context Protokolü aracılığıyla yerleşik içgözlem ve işlem araçlarıyla GraphQL API'lerine bağlayın. GraphQL işlemlerini MCP araçları olarak sunar; üç işlem kaynağını destekler: yerel dosyalar, GraphOS Studio koleksiyonları ve kalıcı sorgu bildirimleri. Şema keşfi ve geçici sorgu testi için dört içgözlem aracı (introspect, search, validate, execute) sağlar; küçültme modu, kompakt notasyonla token kullanımını azaltır. Statik başlıklar aracılığıyla yapılandırılabilir kimlik doğrulama,...
official
apollo-router
apollographql
Apollo Router, Apollo Federation 2 süper grafiklerini çalıştırmak için Rust dilinde yazılmış yüksek performanslı bir grafik yönlendiricisidir. Alt grafiklerinizin önünde yer alır ve sorgu planlaması, yürütme ve yanıt birleştirme işlemlerini yönetir.
official