apollo-server

โดย apollographql

คู่มือฉบับสมบูรณ์สำหรับการสร้างเซิร์ฟเวอร์ GraphQL ด้วย Apollo Server 5.x ในทุกเฟรมเวิร์ก ครอบคลุมการกำหนดสคีมา ตัวแก้ไข การตั้งค่าคอนเทกซ์ และการจัดการข้อผิดพลาดพร้อมรองรับ TypeScript รองรับโหมดสแตนด์อโลนสำหรับการสร้างต้นแบบ และการผสานรวมกับ Express, Fastify, Koa และสภาพแวดล้อมแบบไร้เซิร์ฟเวอร์ รวมถึงรูปแบบตัวแก้ไข การรับรองความถูกต้อง/การอนุญาต ปลั๊กอิน DataLoader สำหรับป้องกันปัญหา N+1 และเทคนิคการปรับปรุงประสิทธิภาพ ให้เอกสารอ้างอิงสำหรับแหล่งข้อมูล ข้อผิดพลาด...

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

Skills เพิ่มเติมจาก apollographql

apollo-client
apollographql
Apollo Client เป็นไลบรารีจัดการสถานะที่ครอบคลุมสำหรับ JavaScript ที่ช่วยให้คุณจัดการข้อมูลทั้งในเครื่องและระยะไกลด้วย GraphQL เวอร์ชัน 4.x นำเสนอการแคชที่ปรับปรุงดีขึ้น การรองรับ TypeScript ที่ดีขึ้น และความเข้ากันได้กับ React 19
official
apollo-client
apollographql
คู่มือที่ครอบคลุมสำหรับการสร้างแอปพลิเคชัน React ด้วย Apollo Client 4.x ครอบคลุมการสอบถาม การกลายพันธุ์ การแคช และการจัดการสถานะ รองรับเฟรมเวิร์ก React และการตั้งค่าหลายแบบ: แอปฝั่งไคลเอ็นต์ (Vite, CRA), Next.js App Router พร้อม React Server Components, React Router 7 พร้อมสตรีมมิ่ง SSR และ TanStack Start รวมถึง hooks สำหรับการสอบถาม (useQuery, useLazyQuery), การกลายพันธุ์ (useMutation) และรูปแบบที่ใช้ Suspense (useSuspenseQuery, useBackgroundQuery) สำหรับ React 18+ และ 19 สมัยใหม่...
official
apollo-connectors
apollographql
รวม REST API เข้ากับ GraphQL supergraphs โดยใช้ @source และ @connect directives มีกระบวนการ 5 ขั้นตอนที่มีโครงสร้าง: ศึกษาโครงสร้าง API, ใช้ schema กับ directives, ตรวจสอบผ่าน rover supergraph compose, ดำเนินการ connectors, และทดสอบครอบคลุม รองรับการกำหนดค่าคำขอรวมถึง headers, body payloads, การทำ batch สำหรับรูปแบบ N+1, และการแทรกตัวแปรสภาพแวดล้อมผ่าน $env จัดการการแมปการตอบสนองด้วยการเลือกฟิลด์, การตั้งชื่ออื่น, การเลือกย่อยสำหรับข้อมูลที่ซ้อนกัน, และ entity...
official
apollo-federation
apollographql
Apollo Federation ช่วยให้สามารถรวม GraphQL API หลายตัว (ซับกราฟ) เข้าด้วยกันเป็นซูเปอร์กราฟแบบรวมศูนย์
official
apollo-ios
apollographql
Apollo iOS เป็น GraphQL ไคลเอนต์แบบ strongly-typed สำหรับแพลตฟอร์ม Apple โดยสร้างประเภท Swift จากการดำเนินการและสคีมา GraphQL ของคุณ และมาพร้อมกับไคลเอนต์แบบ async/await, แคชแบบ normalized (ในหน่วยความจำหรือ backed โดย SQLite), การขนส่ง HTTP แบบ interceptor-based ที่เสียบได้ซึ่งจัดการ queries, mutations, และ multipart subscriptions, และการขนส่ง WebSocket แบบเลือกได้ (graphql-transport-ws) ที่สามารถรองรับการดำเนินการทุกประเภท
official
apollo-kotlin
apollographql
Apollo Kotlin เป็นไคลเอนต์ GraphQL ที่มีการกำหนดชนิดข้อมูลอย่างเข้มงวด ซึ่งสร้างโมเดล Kotlin จากการดำเนินการและสคีมา GraphQL ของคุณ สามารถใช้ในโปรเจกต์ Android, JVM และ Kotlin Multiplatform ได้
official
apollo-mcp-server
apollographql
เชื่อมต่อ AI agents กับ GraphQL APIs ผ่าน Model Context Protocol พร้อมเครื่องมือ introspection และ operation ในตัว เปิดเผย GraphQL operations เป็น MCP tools; รองรับแหล่ง operation สามประเภท: ไฟล์ในเครื่อง, คอลเลกชัน GraphOS Studio, และ persisted query manifests มีเครื่องมือ introspection สี่อย่าง (introspect, search, validate, execute) สำหรับการสำรวจ schema และทดสอบ query แบบ ad-hoc; โหมด minification ลดการใช้ token ด้วยสัญกรณ์แบบกะทัดรัด กำหนดค่าการรับรองความถูกต้องผ่าน static headers,...
official
apollo-router
apollographql
Apollo Router เป็นกราฟเราเตอร์ประสิทธิภาพสูงที่เขียนด้วยภาษา Rust สำหรับรันซูเปอร์กราฟของ Apollo Federation 2 โดยจะอยู่ด้านหน้าซับกราฟของคุณและจัดการการวางแผนคิวรี การดำเนินการ และการประกอบคำตอบ
official