前言

💡 痛点:REST API 冗余数据传输?多端数据需求不一致?前端依赖后端接口变更?

🎯 解决方案:掌握 GraphQL — 让前端精准获取所需数据,一次请求,多端通用。

GraphQL 架构图:

客户端

GraphQL 服务器

Web App

Mobile App

第三方 App

Schema 定义

Resolver 函数

数据源

type Query

type Mutation

type Subscription

数据库

REST API

微服务

缓存

PostgreSQL

MongoDB

Redis

GraphQL vs REST:

特性GraphQLREST
数据获取单次请求,精确字段多次请求,过量数据
版本控制无版本,通过字段演进版本路径 /v1/, /v2/
类型系统强类型 Schema无统一类型
文档自描述(自文档化)需额外 Swagger/OpenAPI
缓存需手动管理HTTP 缓存天然支持
实时订阅原生 Subscription需 WebSocket 扩展

一、GraphQL 基础概念

1.1 什么是 GraphQL

GraphQL

Facebook 2015

API 查询语言

运行时执行引擎

强类型 Schema

开源

社区驱动

GraphQL 三层架构:

GraphQL Schema

类型系统

字段和关系

操作类型

User 类型

Post 类型

Comment 类型

Scalar

Object

Enum

Query 查询

Mutation 变更

Subscription 订阅

1.2 Schema 定义语言(SDL)

# ===== GraphQL Schema 定义 =====

# 定义用户类型
type User {
  id: ID!
  name: String!
  email: String!
  age: Int
  isActive: Boolean!
  createdAt: DateTime!
  updatedAt: DateTime!
  
  # 关系
  posts: [Post!]!
  friends: [User!]!
  followers: [User!]!
  following: [User!]!
}

# 定义文章类型
type Post {
  id: ID!
  title: String!
  slug: String!
  content: String!
  excerpt: String
  coverImage: String
  published: Boolean!
  publishedAt: DateTime
  viewCount: Int!
  readTime: Int!
  createdAt: DateTime!
  updatedAt: DateTime!
  
  # 关系
  author: User!
  comments: [Comment!]!
  tags: [Tag!]!
  likes: [Like!]!
}

# 定义评论类型
type Comment {
  id: ID!
  content: String!
  createdAt: DateTime!
  
  # 关系
  author: User!
  post: Post!
  replies: [Comment!]!
  parent: Comment
}

# 定义标签类型
type Tag {
  id: ID!
  name: String!
  slug: String!
  postCount: Int!
  posts: [Post!]!
}

# 定义点赞类型
type Like {
  id: ID!
  createdAt: DateTime!
  user: User!
  post: Post!
}

# 枚举类型
enum Role {
  ADMIN
  EDITOR
  AUTHOR
  READER
}

# 接口定义
interface Node {
  id: ID!
}

interface Timestamped {
  createdAt: DateTime!
  updatedAt: DateTime!
}

# 标量类型
scalar DateTime
scalar JSON
scalar Upload

# 输入类型(用于 Mutation)
input CreatePostInput {
  title: String!
  content: String!
  slug: String
  coverImage: String
  tagIds: [ID!]
}

input UpdatePostInput {
  title: String
  content: String
  coverImage: String
}

input PaginationInput {
  page: Int! = 1
  limit: Int! = 10
}

input SortInput {
  field: String!
  order: SortOrder! = ASC
}

enum SortOrder {
  ASC
  DESC
}

1.3 操作类型

# ===== Query(查询) =====
type Query {
  # 获取单个用户
  user(id: ID!): User
  
  # 获取当前登录用户
  me: User
  
  # 获取文章列表
  posts(
    filter: PostFilterInput
    pagination: PaginationInput
    sort: SortInput
  ): PostConnection!
  
  # 获取单个文章
  post(id: ID, slug: String): Post
  
  # 获取标签列表
  tags: [Tag!]!
  
  # 获取评论
  comments(postId: ID!): [Comment!]!
}

# 连接类型(用于分页)
type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type PostEdge {
  node: Post!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

# ===== Mutation(变更) =====
type Mutation {
  # 用户相关
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
  
  # 文章相关
  createPost(input: CreatePostInput!): Post!
  updatePost(id: ID!, input: UpdatePostInput!): Post!
  deletePost(id: ID!): Boolean!
  publishPost(id: ID!): Post!
  unpublishPost(id: ID!): Post!
  
  # 评论相关
  createComment(postId: ID!, input: CreateCommentInput!): Comment!
  deleteComment(id: ID!): Boolean!
  
  # 点赞相关
  likePost(postId: ID!): Like!
  unlikePost(postId: ID!): Boolean!
}

# ===== Subscription(订阅) =====
type Subscription {
  # 实时订阅新评论
  commentAdded(postId: ID!): Comment!
  
  # 订阅文章更新
  postUpdated(id: ID!): Post!
  
  # 订阅用户状态
  userStatusChanged(userId: ID!): UserStatus!
}

二、Node.js + Apollo Server 实战

2.1 项目初始化

# ===== 项目初始化 =====

mkdir graphql-server
cd graphql-server

npm init -y

# 安装依赖
npm install @apollo/server graphql graphql-tag
npm install @as-integrations/fastify  # 如果使用 Fastify
npm install express @apollo/server/express4  # 如果使用 Express
npm install @graphql-tools/schema graphql-middleware  # 工具
npm install @prisma/client prisma  # 数据库 ORM
npm install @graphql-auth-directive  # 认证
npm install graphql-scalars  # 扩展标量类型

# 开发依赖
npm install -D typescript @types/node ts-node nodemon
// package.json
{
  "name": "graphql-server",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "nodemon --exec ts-node-esm server.ts",
    "build": "tsc",
    "start": "node dist/server.js",
    "prisma:generate": "prisma generate",
    "prisma:migrate": "prisma migrate dev"
  }
}

2.2 TypeScript 配置

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2.3 Schema 定义

// src/schema/index.ts
import { gql } from 'graphql-tag';

export const typeDefs = gql`
  scalar DateTime

  type User {
    id: ID!
    name: String!
    email: String!
    avatar: String
    bio: String
    role: Role!
    isActive: Boolean!
    createdAt: DateTime!
    updatedAt: DateTime!
    posts: [Post!]!
    postCount: Int!
  }

  type Post {
    id: ID!
    title: String!
    slug: String!
    content: String!
    excerpt: String
    coverImage: String
    published: Boolean!
    publishedAt: DateTime
    viewCount: Int!
    readTime: Int!
    createdAt: DateTime!
    updatedAt: DateTime!
    author: User!
    comments: [Comment!]!
    commentCount: Int!
    tags: [Tag!]!
    isLiked: Boolean!
    likeCount: Int!
  }

  type Comment {
    id: ID!
    content: String!
    createdAt: DateTime!
    author: User!
    post: Post!
    replies: [Comment!]!
    parent: Comment
  }

  type Tag {
    id: ID!
    name: String!
    slug: String!
    color: String
    postCount: Int!
  }

  type Like {
    id: ID!
    createdAt: DateTime!
    user: User!
    post: Post!
  }

  type AuthPayload {
    token: String!
    user: User!
  }

  enum Role {
    ADMIN
    EDITOR
    AUTHOR
    READER
  }

  type Query {
    # 用户
    me: User
    user(id: ID!): User
    users(pagination: PaginationInput): UserConnection!

    # 文章
    post(id: ID, slug: String): Post
    posts(
      filter: PostFilterInput
      pagination: PaginationInput
      sort: SortInput
    ): PostConnection!
    featuredPosts: [Post!]!

    # 标签
    tags: [Tag!]!
    tag(slug: String!): Tag

    # 评论
    comments(postId: ID!): [Comment!]!
  }

  type Mutation {
    # 认证
    login(email: String!, password: String!): AuthPayload!
    register(input: RegisterInput!): AuthPayload!

    # 用户
    updateProfile(input: UpdateProfileInput!): User!

    # 文章
    createPost(input: CreatePostInput!): Post!
    updatePost(id: ID!, input: UpdatePostInput!): Post!
    deletePost(id: ID!): Boolean!
    publishPost(id: ID!): Post!
    unpublishPost(id: ID!): Post!

    # 评论
    createComment(postId: ID!, content: String!, parentId: ID): Comment!
    deleteComment(id: ID!): Boolean!

    # 点赞
    likePost(postId: ID!): Like!
    unlikePost(postId: ID!): Boolean!
  }

  type Subscription {
    commentAdded(postId: ID!): Comment!
    postLiked(postId: ID!): Like!
    postViewed(postId: ID!): Post!
  }

  # 输入类型
  input RegisterInput {
    name: String!
    email: String!
    password: String!
  }

  input UpdateProfileInput {
    name: String
    avatar: String
    bio: String
  }

  input CreatePostInput {
    title: String!
    content: String!
    slug: String
    coverImage: String
    tagIds: [ID!]
  }

  input UpdatePostInput {
    title: String
    content: String
    coverImage: String
    tagIds: [ID!]
  }

  input PostFilterInput {
    search: String
    tagSlugs: [String!]
    authorId: ID
    published: Boolean
    fromDate: DateTime
    toDate: DateTime
  }

  input PaginationInput {
    page: Int = 1
    limit: Int = 10
  }

  input SortInput {
    field: String = "createdAt"
    order: SortOrder = DESC
  }

  enum SortOrder {
    ASC
    DESC
  }

  # 连接类型
  type UserConnection {
    edges: [UserEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
  }

  type UserEdge {
    node: User!
    cursor: String!
  }

  type PostConnection {
    edges: [PostEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
  }

  type PostEdge {
    node: Post!
    cursor: String!
  }

  type PageInfo {
    hasNextPage: Boolean!
    hasPreviousPage: Boolean!
    startCursor: String
    endCursor: String
  }
`;

2.4 Resolver 函数

// src/resolvers/index.ts
import { Context } from '../context';
import { AuthenticationError, ForbiddenError, UserInputError } from '../errors';
import {prisma} from '../lib/prisma';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

export const resolvers = {
  // 标量类型解析
  DateTime: {
    __parseValue(value: string) {
      return new Date(value);
    },
    __serialize(value: Date) {
      return value.toISOString();
    },
    __parseLiteral(ast: any) {
      if (ast.kind === 'StringValue') {
        return new Date(ast.value);
      }
      return null;
    },
  },

  // 查询解析器
  Query: {
    // 当前用户
    me: async (_: any, __: any, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }
      return context.user;
    },

    // 单个用户
    user: async (_: any, { id }: { id: string }, context: Context) => {
      return prisma.user.findUnique({ where: { id } });
    },

    // 用户列表
    users: async (_: any, { pagination }: { pagination: any }, context: Context) => {
      const { page = 1, limit = 10 } = pagination || {};
      const skip = (page - 1) * limit;

      const [users, totalCount] = await Promise.all([
        prisma.user.findMany({
          skip,
          take: limit,
          orderBy: { createdAt: 'desc' },
        }),
        prisma.user.count(),
      ]);

      return {
        edges: users.map((user) => ({ node: user, cursor: Buffer.from(user.id).toString('base64') })),
        pageInfo: {
          hasNextPage: skip + users.length < totalCount,
          hasPreviousPage: page > 1,
        },
        totalCount,
      };
    },

    // 文章
    post: async (_: any, { id, slug }: { id?: string; slug?: string }, context: Context) => {
      return prisma.post.findFirst({
        where: id ? { id } : { slug },
      });
    },

    // 文章列表
    posts: async (_: any, { filter, pagination, sort }: any, context: Context) => {
      const { page = 1, limit = 10 } = pagination || {};
      const { field = 'createdAt', order = 'desc' } = sort || {};
      const skip = (page - 1) * limit;

      // 构建查询条件
      const where: any = {};
      
      if (filter) {
        if (filter.search) {
          where.OR = [
            { title: { contains: filter.search, mode: 'insensitive' } },
            { content: { contains: filter.search, mode: 'insensitive' } },
          ];
        }
        if (filter.tagSlugs) {
          where.tags = {
            some: { slug: { in: filter.tagSlugs } },
          };
        }
        if (filter.authorId) {
          where.authorId = filter.authorId;
        }
        if (filter.published !== undefined) {
          where.published = filter.published;
        }
        if (filter.fromDate) {
          where.createdAt = { ...where.createdAt, gte: new Date(filter.fromDate) };
        }
        if (filter.toDate) {
          where.createdAt = { ...where.createdAt, lte: new Date(filter.toDate) };
        }
      }

      const [posts, totalCount] = await Promise.all([
        prisma.post.findMany({
          where,
          skip,
          take: limit,
          orderBy: { [field]: order },
          include: {
            author: true,
            tags: true,
            _count: { select: { comments: true, likes: true } },
          },
        }),
        prisma.post.count({ where }),
      ]);

      // 判断是否点赞
      const postsWithLikeStatus = posts.map((post) => ({
        ...post,
        isLiked: context.user ? await checkIsLiked(post.id, context.user.id) : false,
      }));

      return {
        edges: postsWithLikeStatus.map((post) => ({
          node: post,
          cursor: Buffer.from(post.id).toString('base64'),
        })),
        pageInfo: {
          hasNextPage: skip + posts.length < totalCount,
          hasPreviousPage: page > 1,
          startCursor: posts[0] ? Buffer.from(posts[0].id).toString('base64') : null,
          endCursor: posts[posts.length - 1] ? Buffer.from(posts[posts.length - 1].id).toString('base64') : null,
        },
        totalCount,
      };
    },

    // 精选文章
    featuredPosts: async (_: any, __: any, context: Context) => {
      return prisma.post.findMany({
        where: { published: true },
        orderBy: { viewCount: 'desc' },
        take: 5,
        include: { author: true, tags: true },
      });
    },

    // 标签列表
    tags: async (_: any, __: any, context: Context) => {
      return prisma.tag.findMany({
        include: { _count: { select: { posts: true } } },
      });
    },

    // 评论列表
    comments: async (_: any, { postId }: { postId: string }, context: Context) => {
      return prisma.comment.findMany({
        where: { postId, parentId: null },
        include: {
          author: true,
          replies: {
            include: { author: true, replies: { include: { author: true } } },
          },
        },
        orderBy: { createdAt: 'desc' },
      });
    },
  },

  // 变更解析器
  Mutation: {
    // 登录
    login: async (_: any, { email, password }: { email: string; password: string }) => {
      const user = await prisma.user.findUnique({ where: { email } });
      
      if (!user || !await bcrypt.compare(password, user.passwordHash)) {
        throw new AuthenticationError('邮箱或密码错误');
      }

      const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET!, {
        expiresIn: '7d',
      });

      return { token, user };
    },

    // 注册
    register: async (_: any, { input }: { input: any }) => {
      const existingUser = await prisma.user.findUnique({
        where: { email: input.email },
      });

      if (existingUser) {
        throw new UserInputError('该邮箱已被注册');
      }

      const passwordHash = await bcrypt.hash(input.password, 10);

      const user = await prisma.user.create({
        data: {
          name: input.name,
          email: input.email,
          passwordHash,
          role: 'AUTHOR',
        },
      });

      const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET!, {
        expiresIn: '7d',
      });

      return { token, user };
    },

    // 创建文章
    createPost: async (_: any, { input }: { input: any }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const slug = input.slug || generateSlug(input.title);

      const post = await prisma.post.create({
        data: {
          title: input.title,
          slug,
          content: input.content,
          coverImage: input.coverImage,
          authorId: context.user.id,
          published: false,
        },
        include: { author: true, tags: true },
      });

      // 添加标签
      if (input.tagIds && input.tagIds.length > 0) {
        await prisma.post.update({
          where: { id: post.id },
          data: {
            tags: { connect: input.tagIds.map((id: string) => ({ id })) },
          },
        });
      }

      return post;
    },

    // 更新文章
    updatePost: async (_: any, { id, input }: { id: string; input: any }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const post = await prisma.post.findUnique({ where: { id } });

      if (!post) {
        throw new UserInputError('文章不存在');
      }

      if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
        throw new ForbiddenError('无权限修改此文章');
      }

      const updatedPost = await prisma.post.update({
        where: { id },
        data: {
          title: input.title,
          content: input.content,
          coverImage: input.coverImage,
        },
        include: { author: true, tags: true },
      });

      // 更新标签
      if (input.tagIds) {
        await prisma.post.update({
          where: { id },
          data: {
            tags: { set: input.tagIds.map((id: string) => ({ id })) },
          },
        });
      }

      return updatedPost;
    },

    // 删除文章
    deletePost: async (_: any, { id }: { id: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const post = await prisma.post.findUnique({ where: { id } });

      if (!post) {
        throw new UserInputError('文章不存在');
      }

      if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
        throw new ForbiddenError('无权限删除此文章');
      }

      await prisma.post.delete({ where: { id } });
      return true;
    },

    // 发布文章
    publishPost: async (_: any, { id }: { id: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      return prisma.post.update({
        where: { id },
        data: { published: true, publishedAt: new Date() },
        include: { author: true, tags: true },
      });
    },

    // 创建评论
    createComment: async (_: any, { postId, content, parentId }: any, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const comment = await prisma.comment.create({
        data: {
          content,
          postId,
          authorId: context.user.id,
          parentId,
        },
        include: { author: true, post: true },
      });

      return comment;
    },

    // 点赞
    likePost: async (_: any, { postId }: { postId: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const existing = await prisma.like.findFirst({
        where: { postId, userId: context.user.id },
      });

      if (existing) {
        return existing;
      }

      return prisma.like.create({
        data: { postId, userId: context.user.id },
        include: { user: true, post: true },
      });
    },

    // 取消点赞
    unlikePost: async (_: any, { postId }: { postId: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      await prisma.like.deleteMany({
        where: { postId, userId: context.user.id },
      });

      return true;
    },
  },

  // 订阅解析器
  Subscription: {
    commentAdded: {
      subscribe: async function* (_, { postId }: any) {
        for await (const comment of commentIterator(postId)) {
          yield { commentAdded: comment };
        }
      },
    },
  },

  // 类型解析器
  User: {
    posts: async (parent: any) => {
      return prisma.post.findMany({
        where: { authorId: parent.id, published: true },
        orderBy: { createdAt: 'desc' },
      });
    },
    postCount: async (parent: any) => {
      return prisma.post.count({ where: { authorId: parent.id, published: true } });
    },
  },

  Post: {
    author: async (parent: any) => {
      return prisma.user.findUnique({ where: { id: parent.authorId } });
    },
    comments: async (parent: any) => {
      return prisma.comment.findMany({
        where: { postId: parent.id, parentId: null },
        orderBy: { createdAt: 'desc' },
      });
    },
    commentCount: async (parent: any) => {
      return prisma.comment.count({ where: { postId: parent.id } });
    },
    tags: async (parent: any) => {
      return prisma.tag.findMany({
        where: { posts: { some: { id: parent.id } } },
      });
    },
    likeCount: async (parent: any) => {
      return prisma.like.count({ where: { postId: parent.id } });
    },
    readTime: (parent: any) => {
      const wordsPerMinute = 200;
      const wordCount = parent.content.split(/\s+/).length;
      return Math.ceil(wordCount / wordsPerMinute);
    },
  },

  Tag: {
    postCount: async (parent: any) => {
      return prisma.post.count({
        where: { published: true, tags: { some: { id: parent.id } } },
      });
    },
  },
};

// 辅助函数
async function checkIsLiked(postId: string, userId: string): Promise<boolean> {
  const like = await prisma.like.findFirst({
    where: { postId, userId },
  });
  return !!like;
}

function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '');
}

async function* commentIterator(postId: string) {
  // 实现 PubSub 逻辑
}

2.5 Context 与认证

// src/context.ts
import { PrismaClient } from '@prisma/client';
import { User } from '@prisma/client';
import jwt from 'jsonwebtoken';

export interface Context {
  prisma: PrismaClient;
  user: User | null;
}

export async function createContext(req: any): Promise<Context> {
  const prisma = new PrismaClient();

  // 从 Authorization Header 获取 token
  const authHeader = req.headers.authorization || '';
  const token = authHeader.replace('Bearer ', '');

  let user = null;

  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string };
      user = await prisma.user.findUnique({ where: { id: decoded.userId } });
    } catch (error) {
      // token 无效,继续以游客身份
    }
  }

  return { prisma, user };
}

2.6 服务器入口

// src/server.ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import cors from 'cors';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
import { createContext } from './context';

const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true, // 开发环境开启
  formatError: (error) => {
    // 生产环境移除 stack trace
    if (process.env.NODE_ENV === 'production') {
      return {
        message: error.message,
        path: error.path,
      };
    }
    return error;
  },
});

await server.start();

app.use(
  '/graphql',
  cors<cors.CorsRequest>(),
  express.json({ limit: '10mb' }),
  expressMiddleware(server, {
    context: async ({ req }) => createContext(req),
  })
);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
  console.log(`🚀 GraphQL Server ready at http://localhost:${PORT}/graphql`);
});

三、Prisma 数据库集成

3.1 Prisma Schema

// prisma/schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id           String    @id @default(cuid())
  email        String    @unique
  name         String
  passwordHash String
  avatar       String?
  bio          String?
  role         Role      @default(AUTHOR)
  isActive     Boolean   @default(true)
  createdAt    DateTime  @default(now())
  updatedAt    DateTime  @updatedAt

  posts    Post[]
  comments Comment[]
  likes    Like[]
}

model Post {
  id          String    @id @default(cuid())
  title       String
  slug        String    @unique
  content     String
  excerpt     String?
  coverImage  String?
  published   Boolean   @default(false)
  publishedAt DateTime?
  viewCount   Int       @default(0)
  readTime    Int       @default(0)
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt

  authorId String
  author   User   @relation(fields: [authorId], references: [id])

  tags     Tag[]
  comments Comment[]
  likes    Like[]

  @@index([authorId])
  @@index([published])
  @@index([slug])
}

model Tag {
  id        String   @id @default(cuid())
  name      String
  slug      String   @unique
  color     String?
  createdAt DateTime @default(now())

  posts Post[]
}

model Comment {
  id        String   @id @default(cuid())
  content   String
  createdAt DateTime @default(now())

  postId String
  post   Post   @relation(fields: [postId], references: [id], onDelete: Cascade)

  authorId String
  author   User   @relation(fields: [authorId], references: [id])

  parentId String?
  parent   Comment?  @relation("CommentReplies", fields: [parentId], references: [id])
  replies  Comment[] @relation("CommentReplies")

  @@index([postId])
  @@index([authorId])
}

model Like {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now())

  postId String
  post   Post   @relation(fields: [postId], references: [id], onDelete: Cascade)

  userId String
  user   User   @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([postId, userId])
}

enum Role {
  ADMIN
  EDITOR
  AUTHOR
  READER
}

3.2 Prisma 客户端

// src/lib/prisma.ts
import { PrismaClient } from '@prisma/client';

declare global {
  var __prisma: PrismaClient | undefined;
}

export const prisma =
  global.__prisma ||
  new PrismaClient({
    log: process.env.NODE_ENV === 'development'
      ? ['query', 'error', 'warn']
      : ['error'],
  });

if (process.env.NODE_ENV !== 'production') {
  global.__prisma = prisma;
}

四、前端集成(React + Apollo Client)

4.1 Apollo Client 配置

// src/lib/apollo-client.ts
import { ApolloClient, InMemoryCache, createHttpLink, from } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { createClient } from 'graphql-ws';

const httpLink = createHttpLink({
  uri: process.env.NEXT_PUBLIC_GRAPHQL_URL || 'http://localhost:4000/graphql',
});

// Auth Link
const authLink = setContext((_, { headers }) => {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

// Error Link
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) => {
      console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
      
      if (message === '请先登录') {
        // 处理未登录
        localStorage.removeItem('token');
        window.location.href = '/login';
      }
    });
  }

  if (networkError) {
    console.error(`[Network error]: ${networkError}`);
  }
});

// Subscription Link (WebSocket)
const wsLink = typeof window !== 'undefined'
  ? new GraphQLWsLink(
      createClient({
        url: process.env.NEXT_PUBLIC_GRAPHQL_WS_URL || 'ws://localhost:4000/graphql',
        connectionParams: () => ({
          Authorization: localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : '',
        }),
      })
    )
  : null;

// Split Link
const splitLink = typeof window !== 'undefined' && wsLink
  ? split(({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      );
    }, wsLink, authLink.concat(httpLink))
  : authLink.concat(httpLink);

// Cache
const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        posts: {
          keyArgs: ['filter'],
          merge(existing, incoming, { args }) {
            if (!args?.pagination?.page || args.pagination.page === 1) {
              return incoming;
            }
            return {
              ...incoming,
              edges: [...(existing?.edges || []), ...incoming.edges],
            };
          },
        },
      },
    },
    Post: {
      fields: {
        isLiked: {
          merge(_, incoming) {
            return incoming;
          },
        },
        likeCount: {
          merge(_, incoming) {
            return incoming;
          },
        },
      },
    },
  },
});

export const apolloClient = new ApolloClient({
  link: from([errorLink, splitLink]),
  cache,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
  },
});

4.2 React Hooks 封装

// src/hooks/useGraphQL.ts
import { useQuery, useMutation, useSubscription } from '@apollo/client';
import { gql } from '@apollo/client';

// ===== 查询 Hooks =====

// 获取文章列表
export function usePosts(filter?: any, pagination?: any, sort?: any) {
  return useQuery(GET_POSTS, {
    variables: { filter, pagination, sort },
    notifyOnNetworkStatusChange: true,
  });
}

// 获取单篇文章
export function usePost(id?: string, slug?: string) {
  return useQuery(GET_POST, {
    variables: { id, slug },
    skip: !id && !slug,
  });
}

// 获取当前用户
export function useCurrentUser() {
  return useQuery(GET_CURRENT_USER);
}

// 获取标签列表
export function useTags() {
  return useQuery(GET_TAGS);
}

// ===== 变更 Hooks =====

// 登录
export function useLogin() {
  return useMutation(LOGIN, {
    onCompleted: (data) => {
      localStorage.setItem('token', data.login.token);
    },
  });
}

// 注册
export function useRegister() {
  return useMutation(REGISTER, {
    onCompleted: (data) => {
      localStorage.setItem('token', data.register.token);
    },
  });
}

// 创建文章
export function useCreatePost() {
  return useMutation(CREATE_POST, {
    refetchQueries: [{ query: GET_POSTS }],
  });
}

// 更新文章
export function useUpdatePost() {
  return useMutation(UPDATE_POST, {
    refetchQueries: [{ query: GET_POSTS }, { query: GET_POST }],
  });
}

// 点赞
export function useLikePost() {
  return useMutation(LIKE_POST, {
    optimisticResponse: {
      likePost: {
        __typename: 'Like',
        id: 'temp-id',
      },
    },
    update: (cache, { data: { likePost } }) => {
      // 更新缓存
    },
  });
}

// ===== 订阅 Hooks =====

// 订阅新评论
export function useCommentSubscription(postId: string) {
  return useSubscription(COMMENT_SUBSCRIPTION, {
    variables: { postId },
  });
}

// ===== GraphQL 文档 =====

const GET_POSTS = gql`
  query GetPosts($filter: PostFilterInput, $pagination: PaginationInput, $sort: SortInput) {
    posts(filter: $filter, pagination: $pagination, sort: $sort) {
      edges {
        node {
          id
          title
          slug
          excerpt
          coverImage
          published
          viewCount
          readTime
          createdAt
          author {
            id
            name
            avatar
          }
          tags {
            id
            name
            slug
          }
          commentCount
          likeCount
          isLiked
        }
      }
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
      totalCount
    }
  }
`;

const GET_POST = gql`
  query GetPost($id: ID, $slug: String) {
    post(id: $id, slug: $slug) {
      id
      title
      slug
      content
      excerpt
      coverImage
      published
      publishedAt
      viewCount
      readTime
      createdAt
      author {
        id
        name
        avatar
        bio
      }
      tags {
        id
        name
        slug
        color
      }
      comments {
        id
        content
        createdAt
        author {
          id
          name
          avatar
        }
        replies {
          id
          content
          createdAt
          author {
            id
            name
            avatar
          }
        }
      }
      commentCount
      likeCount
      isLiked
    }
  }
`;

const GET_CURRENT_USER = gql`
  query GetCurrentUser {
    me {
      id
      name
      email
      avatar
      bio
      role
    }
  }
`;

const GET_TAGS = gql`
  query GetTags {
    tags {
      id
      name
      slug
      color
      postCount
    }
  }
`;

const LOGIN = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
      user {
        id
        name
        email
      }
    }
  }
`;

const REGISTER = gql`
  mutation Register($input: RegisterInput!) {
    register(input: $input) {
      token
      user {
        id
        name
        email
      }
    }
  }
`;

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      id
      title
      slug
    }
  }
`;

const UPDATE_POST = gql`
  mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
    updatePost(id: $id, input: $input) {
      id
      title
      slug
      content
    }
  }
`;

const LIKE_POST = gql`
  mutation LikePost($postId: ID!) {
    likePost(postId: $postId) {
      id
      post {
        id
        likeCount
      }
    }
  }
`;

const COMMENT_SUBSCRIPTION = gql`
  subscription CommentAdded($postId: ID!) {
    commentAdded(postId: $postId) {
      id
      content
      createdAt
      author {
        id
        name
        avatar
      }
    }
  }
`;

4.3 React 组件示例

// src/components/PostList.tsx
import { usePosts } from '@/hooks/useGraphQL';
import { Link } from 'next/link';
import { useRouter } from 'next/navigation';

export function PostList() {
  const router = useRouter();
  const { data, loading, error, fetchMore } = usePosts(
    { published: true },
    { page: 1, limit: 10 },
    { field: 'createdAt', order: 'DESC' }
  );

  if (loading && !data) return <PostListSkeleton />;
  if (error) return <ErrorMessage error={error} />;

  const { posts } = data;
  const { edges, pageInfo, totalCount } = posts;

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">文章列表</h1>
        <span className="text-gray-500">共 {totalCount} 篇</span>
      </div>

      <div className="grid gap-6">
        {edges.map(({ node: post }: any) => (
          <PostCard key={post.id} post={post} />
        ))}
      </div>

      {pageInfo.hasNextPage && (
        <div className="text-center mt-8">
          <button
            onClick={() => {
              fetchMore({
                variables: {
                  pagination: { page: Math.ceil(edges.length / 10) + 1, limit: 10 },
                },
              });
            }}
            disabled={loading}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {loading ? '加载中...' : '加载更多'}
          </button>
        </div>
      )}
    </div>
  );
}

function PostCard({ post }: { post: any }) {
  return (
    <article className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition">
      {post.coverImage && (
        <img
          src={post.coverImage}
          alt={post.title}
          className="w-full h-48 object-cover"
        />
      )}
      
      <div className="p-6">
        <div className="flex gap-2 mb-3">
          {post.tags.map((tag: any) => (
            <Link
              key={tag.id}
              href={`/tags/${tag.slug}`}
              className="px-2 py-1 text-xs bg-gray-100 rounded-full hover:bg-gray-200"
            >
              {tag.name}
            </Link>
          ))}
        </div>
        
        <Link href={`/posts/${post.slug}`}>
          <h2 className="text-xl font-bold mb-2 hover:text-blue-600">
            {post.title}
          </h2>
        </Link>
        
        {post.excerpt && (
          <p className="text-gray-600 mb-4 line-clamp-2">{post.excerpt}</p>
        )}
        
        <div className="flex items-center justify-between text-sm text-gray-500">
          <div className="flex items-center gap-2">
            <img
              src={post.author.avatar || '/default-avatar.png'}
              alt={post.author.name}
              className="w-6 h-6 rounded-full"
            />
            <span>{post.author.name}</span>
          </div>
          
          <div className="flex items-center gap-4">
            <span>{new Date(post.createdAt).toLocaleDateString()}</span>
            <span>{post.readTime} 分钟阅读</span>
            <span>{post.likeCount} 点赞</span>
            <span>{post.commentCount} 评论</span>
          </div>
        </div>
      </div>
    </article>
  );
}
// src/components/CreatePostForm.tsx
'use client';

import { useState } from 'react';
import { useCreatePost, useTags } from '@/hooks/useGraphQL';
import { useRouter } from 'next/navigation';

export function CreatePostForm() {
  const router = useRouter();
  const [createPost, { loading }] = useCreatePost();
  const { data: tagsData } = useTags();
  
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    coverImage: '',
    tagIds: [] as string[],
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const { data } = await createPost({
        variables: { input: formData },
      });
      
      router.push(`/posts/${data.createPost.slug}`);
    } catch (error) {
      console.error('创建文章失败:', error);
    }
  };

  const handleTagChange = (tagId: string) => {
    setFormData((prev) => ({
      ...prev,
      tagIds: prev.tagIds.includes(tagId)
        ? prev.tagIds.filter((id) => id !== tagId)
        : [...prev.tagIds, tagId],
    }));
  };

  return (
    <form onSubmit={handleSubmit} className="max-w-2xl mx-auto space-y-6">
      <div>
        <label htmlFor="title" className="block mb-2 font-medium">
          标题
        </label>
        <input
          type="text"
          id="title"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg"
          required
        />
      </div>

      <div>
        <label htmlFor="content" className="block mb-2 font-medium">
          内容
        </label>
        <textarea
          id="content"
          value={formData.content}
          onChange={(e) => setFormData({ ...formData, content: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg min-h-[300px]"
          required
        />
      </div>

      <div>
        <label htmlFor="coverImage" className="block mb-2 font-medium">
          封面图片 URL
        </label>
        <input
          type="url"
          id="coverImage"
          value={formData.coverImage}
          onChange={(e) => setFormData({ ...formData, coverImage: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg"
          placeholder="https://..."
        />
      </div>

      <div>
        <label className="block mb-2 font-medium">标签</label>
        <div className="flex flex-wrap gap-2">
          {tagsData?.tags?.map((tag: any) => (
            <button
              key={tag.id}
              type="button"
              onClick={() => handleTagChange(tag.id)}
              className={`px-3 py-1 rounded-full text-sm ${
                formData.tagIds.includes(tag.id)
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 hover:bg-gray-200'
              }`}
            >
              {tag.name}
            </button>
          ))}
        </div>
      </div>

      <button
        type="submit"
        disabled={loading}
        className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
      >
        {loading ? '创建中...' : '创建文章'}
      </button>
    </form>
  );
}

五、数据加载器(DataLoader)

5.1 N+1 问题与解决

// src/loaders/index.ts
import DataLoader from 'dataloader';
import { prisma } from '../lib/prisma';

// 用户数据加载器
export const createUserLoader = () =>
  new DataLoader<string, any>(async (ids) => {
    const users = await prisma.user.findMany({
      where: { id: { in: ids } },
    });
    
    const userMap = new Map(users.map((user) => [user.id, user]));
    
    return ids.map((id) => userMap.get(id) || null);
  });

// 文章数据加载器
export const createPostLoader = () =>
  new DataLoader<string, any>(async (ids) => {
    const posts = await prisma.post.findMany({
      where: { id: { in: ids } },
      include: { author: true, tags: true },
    });
    
    const postMap = new Map(posts.map((post) => [post.id, post]));
    
    return ids.map((id) => postMap.get(id) || null);
  });

// 评论数量加载器
export const createCommentCountLoader = () =>
  new DataLoader<string, number>(async (postIds) => {
    const counts = await prisma.comment.groupBy({
      by: ['postId'],
      _count: { postId: true },
      where: { postId: { in: postIds } },
    });
    
    const countMap = new Map(counts.map((c) => [c.postId, c._count.postId]));
    
    return postIds.map((id) => countMap.get(id) || 0);
  });

// 点赞数量加载器
export const createLikeCountLoader = () =>
  new DataLoader<string, number>(async (postIds) => {
    const counts = await prisma.like.groupBy({
      by: ['postId'],
      _count: { postId: true },
      where: { postId: { in: postIds } },
    });
    
    const countMap = new Map(counts.map((c) => [c.postId, c._count.postId]));
    
    return postIds.map((id) => countMap.get(id) || 0);
  });
// 在 Context 中注入 Loader
// src/context.ts

import { PrismaClient } from '@prisma/client';
import { createUserLoader, createPostLoader } from './loaders';

export interface Context {
  prisma: PrismaClient;
  user: User | null;
  loaders: {
    user: ReturnType<typeof createUserLoader>;
    post: ReturnType<typeof createPostLoader>;
  };
}

export async function createContext(req: any): Promise<Context> {
  const prisma = new PrismaClient();
  
  // ... 认证逻辑 ...
  
  return {
    prisma,
    user,
    loaders: {
      user: createUserLoader(),
      post: createPostLoader(),
    },
  };
}

5.2 在 Resolver 中使用 Loader

// src/resolvers/post.ts

export const Post = {
  author: async (parent: any, _: any, { loaders }: Context) => {
    // 使用 DataLoader 批量加载
    return loaders.user.load(parent.authorId);
  },
  
  commentCount: async (parent: any, _: any, { loaders }: Context) => {
    return loaders.commentCount.load(parent.id);
  },
  
  likeCount: async (parent: any, _: any, { loaders }: Context) => {
    return loaders.likeCount.load(parent.id);
  },
};

六、中间件与权限控制

6.1 GraphQL 中间件

// src/middleware/authorization.ts
import { AuthenticationError, ForbiddenError } from '../errors';

// 检查是否登录
export function requireAuth(resolver: any) {
  return (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    return resolver(root, args, context, info);
  };
}

// 检查管理员权限
export function requireAdmin(resolver: any) {
  return (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    if (context.user.role !== 'ADMIN') {
      throw new ForbiddenError('需要管理员权限');
    }
    return resolver(root, args, context, info);
  };
}

// 检查文章所有权
export function requirePostOwner(resolver: any) {
  return async (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    
    const post = await context.prisma.post.findUnique({
      where: { id: args.id },
    });
    
    if (!post) {
      throw new UserInputError('文章不存在');
    }
    
    if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
      throw new ForbiddenError('无权限修改此文章');
    }
    
    return resolver(root, args, context, info);
  };
}

// 字段级中间件示例
export const fieldMiddleware = {
  Mutation: {
    // 所有 Mutation 需要登录
    '*': requireAuth,
    
    // 例外情况
    login: (resolver) => resolver,
    register: (resolver) => resolver,
  },
};

6.2 Schema 指令(Directive)

# src/directives/auth.graphql

# 认证指令
directive @auth on FIELD_DEFINITION | OBJECT

# 管理员指令
directive @admin on FIELD_DEFINITION | OBJECT

# 速率限制指令
directive @rateLimit(max: Int!, window: String!) on FIELD_DEFINITION

# 弃用指令(内置)
directive @deprecated(reason: String) on FIELD_DEFINITION | ENUM_VALUE

# 使用示例
type Query {
  # 公开查询
  posts: [Post!]!
  
  # 需要登录
  me: User @auth
  
  # 需要管理员
  users: [User!]! @admin
}

type Mutation {
  # 需要登录
  createPost(input: CreatePostInput!): Post! @auth
  
  # 速率限制
  login(email: String!, password: String!): AuthPayload! @rateLimit(max: 5, window: "5m")
}

七、性能优化

7.1 查询复杂度限制

// src/utils/queryComplexity.ts
import { createComplexityLimitRule } from 'graphql-query-complexity';
import { specifiedRules, validate } from 'graphql';
import { GraphQLError } from 'graphql';

const complexityRule = createComplexityLimitRule(1000, {
  onCost: (cost) => {
    console.log(`Query cost: ${cost}`);
  },
  formatErrorErrorMessage: (cost) => {
    return `Query cost ${cost} exceeds maximum allowed cost of 1000`;
  },
  formatError: (error) => {
    return new GraphQLError(
      'Your query is too complex. Please simplify it.',
      undefined,
      undefined,
      undefined,
      undefined,
      error
    );
  },
});

export { complexityRule };

7.2 响应缓存

// src/middleware/responseCache.ts
import { responseCachePlugin } from '@apollo/server-plugin-response-cache';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    responseCachePlugin({
      sessionId: (requestContext) => {
        // 基于用户 ID 缓存
        return requestContext.context.user?.id || 'anonymous';
      },
    }),
  ],
});

// 或者使用 Redis 缓存
import RedisStore from 'apollo-server-plugin-response-cache-redis';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    responseCachePlugin({
      store: new RedisStore({
        redis: new Redis(process.env.REDIS_URL),
        ttl: 60 * 60, // 1 hour
      }),
    }),
  ],
});

7.3 Persisted Queries

// 客户端:使用 APQ (Automatic Persisted Queries)
import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from '@apollo/client';
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries';
import { sha256 } from 'crypto-hash';

const persistedQueriesLink = createPersistedQueryLink({ sha256 });

const client = new ApolloClient({
  link: ApolloLink.from([
    persistedQueriesLink,
    new HttpLink({ uri: '/graphql' }),
  ]),
  cache: new InMemoryCache(),
});

八、实战:完整的 GraphQL API

8.1 项目结构

graphql-api/
├── src/
│   ├── schema/
│   │   ├── index.ts          # 类型定义
│   │   ├── typeDefs/         # 分类型定义
│   │   │   ├── user.ts
│   │   │   ├── post.ts
│   │   │   ├── comment.ts
│   │   │   └── common.ts
│   │   └── directives/       # 自定义指令
│   │       └── auth.ts
│   ├── resolvers/
│   │   ├── index.ts          # 解析器入口
│   │   ├── Query/            # 查询解析器
│   │   ├── Mutation/         # 变更解析器
│   │   ├── Subscription/     # 订阅解析器
│   │   └── types/            # 类型解析器
│   ├── context.ts
│   ├── errors.ts
│   ├── loaders/              # DataLoader
│   ├── middleware/           # 中间件
│   ├── lib/
│   │   ├── prisma.ts
│   │   ├── redis.ts
│   │   └── utils.ts
│   └── server.ts
├── prisma/
│   └── schema.prisma
├── tests/
└── package.json

8.2 完整服务器代码

// src/server.ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import express from 'express';
import cors from 'cors';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
import { createContext, Context } from './context';
import { complexityRule } from './utils/queryComplexity';
import { responseCachePlugin } from './apollo-server-plugin-response-cache';

async function main() {
  const app = express();

  const server = new ApolloServer<Context>({
    typeDefs,
    resolvers,
    introspection: process.env.NODE_ENV !== 'production',
    validationRules: [complexityRule],
    plugins: [
      ApolloServerPluginCacheControl({
        defaultMaxAge: 60, // 60 秒
        calculateHttpHeaders: true,
      }),
      ApolloServerPluginLandingPageLocalDefault({
        includeCookies: true,
      }),
      responseCachePlugin(),
    ],
  });

  await server.start();

  app.use(
    '/graphql',
    cors<cors.CorsRequest>({
      origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
      credentials: true,
    }),
    express.json({ limit: '10mb' }),
    expressMiddleware(server, {
      context: async ({ req }) => createContext(req),
      formatError: (error) => {
        // 生产环境错误处理
        if (process.env.NODE_ENV === 'production') {
          return {
            message: error.message,
            path: error.path,
          };
        }
        return error;
      },
    })
  );

  // 健康检查
  app.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
  });

  const PORT = process.env.PORT || 4000;

  app.listen(PORT, () => {
    console.log(`
🚀 GraphQL Server ready!
   📍 Local:      http://localhost:${PORT}/graphql
   📍 Studio:     http://studio.apollographql.com/sandbox
   🌐 Environment: ${process.env.NODE_ENV || 'development'}
    `);
  });
}

main().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});

九、测试

9.1 Jest 测试配置

// tests/setup.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

beforeAll(async () => {
  // 清理并填充测试数据
  await prisma.comment.deleteMany();
  await prisma.like.deleteMany();
  await prisma.post.deleteMany();
  await prisma.user.deleteMany();
  
  // 创建测试用户
  await prisma.user.create({
    data: {
      id: 'test-user-1',
      email: 'test@example.com',
      name: 'Test User',
      passwordHash: '$2a$10$...',
      role: 'AUTHOR',
    },
  });
});

afterAll(async () => {
  await prisma.$disconnect();
});

9.2 GraphQL 测试

// tests/graphql.test.ts
import { ApolloServer } from '@apollo/server';
import { typeDefs } from '../src/schema';
import { resolvers } from '../src/resolvers';
import { createContext } from '../src/context';

describe('GraphQL API', () => {
  let server: ApolloServer;
  let testContext: { prisma: PrismaClient; user: any };

  beforeAll(async () => {
    testContext = await createTestContext();
    server = new ApolloServer({
      typeDefs,
      resolvers,
    });
  });

  afterAll(async () => {
    await server.stop();
  });

  describe('Query', () => {
    it('should return posts', async () => {
      const query = `
        query GetPosts {
          posts {
            edges {
              node {
                id
                title
                author {
                  name
                }
              }
            }
          }
        }
      `;

      const response = await server.executeOperation(
        { query },
        { contextValue: testContext }
      );

      expect(response.body.kind).toBe('single');
      if (response.body.kind === 'single') {
        expect(response.body.singleResult.errors).toBeUndefined();
        expect(response.body.singleResult.data?.posts.edges).toBeDefined();
      }
    });
  });

  describe('Mutation', () => {
    it('should create a post', async () => {
      const mutation = `
        mutation CreatePost($input: CreatePostInput!) {
          createPost(input: $input) {
            id
            title
            slug
          }
        }
      `;

      const response = await server.executeOperation(
        {
          query: mutation,
          variables: {
            input: {
              title: 'Test Post',
              content: 'Test content',
            },
          },
        },
        { contextValue: testContext }
      );

      expect(response.body.kind).toBe('single');
      if (response.body.kind === 'single') {
        expect(response.body.singleResult.data?.createPost.title).toBe('Test Post');
      }
    });
  });
});

十、总结

10.1 GraphQL 核心知识点

GraphQL

基础

Schema 定义

Query 查询

Mutation 变更

Subscription 订阅

进阶

Resolver 函数

Context 上下文

DataLoader

中间件

工具

Apollo Server

Prisma

Apollo Client

GraphQL Yoga

性能

查询复杂度

响应缓存

Persisted Queries

N+1 解决

10.2 GraphQL vs REST 对比

维度GraphQLREST
数据获取单次请求,精确字段多次请求或过量数据
类型系统强类型 Schema无统一类型
版本控制通过字段演进URL 版本 /v1/
文档自文档化需 Swagger
缓存手动管理HTTP 缓存
实时SubscriptionWebSocket
学习曲线较陡平缓
适用场景多端 API、灵活查询简单 CRUD

10.3 最佳实践

实践说明
Schema First先设计 Schema,再实现
Naming Convention统一命名风格
Pagination使用 Connection 模式
Error Handling统一错误格式
AuthenticationJWT + 中间件
CachingDataLoader + Redis
Rate Limiting查询复杂度限制

10.4 学习路径

阶段内容资源
入门Schema、Query、MutationApollo 文档
进阶Resolver、Context、DataLoaderGraphQL 规范
实战Apollo Server + PrismaGitHub 示例
生产性能优化、安全Apollo 最佳实践

10.5 推荐资源

类型资源说明
官方文档graphql.orgGraphQL 规范
Apolloapollographql.comGraphQL 平台
Prismaprisma.io数据库 ORM
Yogathe-guild.dev/graphql/yoga轻量级服务器
GraphQL Code Generatorthe-guild.dev/graphql/codegen代码生成

本文基于 Apollo Server 4 + Prisma + React Apollo Client 编写。如有问题欢迎评论区讨论!# GraphQL 实战:从入门到精通

前言

💡 痛点:REST API 冗余数据传输?多端数据需求不一致?前端依赖后端接口变更?

🎯 解决方案:掌握 GraphQL — 让前端精准获取所需数据,一次请求,多端通用。

GraphQL 架构图:

客户端

GraphQL 服务器

Web App

Mobile App

第三方 App

Schema 定义

Resolver 函数

数据源

type Query

type Mutation

type Subscription

数据库

REST API

微服务

缓存

PostgreSQL

MongoDB

Redis

GraphQL vs REST:

特性GraphQLREST
数据获取单次请求,精确字段多次请求,过量数据
版本控制无版本,通过字段演进版本路径 /v1/, /v2/
类型系统强类型 Schema无统一类型
文档自描述(自文档化)需额外 Swagger/OpenAPI
缓存需手动管理HTTP 缓存天然支持
实时订阅原生 Subscription需 WebSocket 扩展

一、GraphQL 基础概念

1.1 什么是 GraphQL

GraphQL

Facebook 2015

API 查询语言

运行时执行引擎

强类型 Schema

开源

社区驱动

GraphQL 三层架构:

GraphQL Schema

类型系统

字段和关系

操作类型

User 类型

Post 类型

Comment 类型

Scalar

Object

Enum

Query 查询

Mutation 变更

Subscription 订阅

1.2 Schema 定义语言(SDL)

# ===== GraphQL Schema 定义 =====

# 定义用户类型
type User {
  id: ID!
  name: String!
  email: String!
  age: Int
  isActive: Boolean!
  createdAt: DateTime!
  updatedAt: DateTime!
  
  # 关系
  posts: [Post!]!
  friends: [User!]!
  followers: [User!]!
  following: [User!]!
}

# 定义文章类型
type Post {
  id: ID!
  title: String!
  slug: String!
  content: String!
  excerpt: String
  coverImage: String
  published: Boolean!
  publishedAt: DateTime
  viewCount: Int!
  readTime: Int!
  createdAt: DateTime!
  updatedAt: DateTime!
  
  # 关系
  author: User!
  comments: [Comment!]!
  tags: [Tag!]!
  likes: [Like!]!
}

# 定义评论类型
type Comment {
  id: ID!
  content: String!
  createdAt: DateTime!
  
  # 关系
  author: User!
  post: Post!
  replies: [Comment!]!
  parent: Comment
}

# 定义标签类型
type Tag {
  id: ID!
  name: String!
  slug: String!
  postCount: Int!
  posts: [Post!]!
}

# 定义点赞类型
type Like {
  id: ID!
  createdAt: DateTime!
  user: User!
  post: Post!
}

# 枚举类型
enum Role {
  ADMIN
  EDITOR
  AUTHOR
  READER
}

# 接口定义
interface Node {
  id: ID!
}

interface Timestamped {
  createdAt: DateTime!
  updatedAt: DateTime!
}

# 标量类型
scalar DateTime
scalar JSON
scalar Upload

# 输入类型(用于 Mutation)
input CreatePostInput {
  title: String!
  content: String!
  slug: String
  coverImage: String
  tagIds: [ID!]
}

input UpdatePostInput {
  title: String
  content: String
  coverImage: String
}

input PaginationInput {
  page: Int! = 1
  limit: Int! = 10
}

input SortInput {
  field: String!
  order: SortOrder! = ASC
}

enum SortOrder {
  ASC
  DESC
}

1.3 操作类型

# ===== Query(查询) =====
type Query {
  # 获取单个用户
  user(id: ID!): User
  
  # 获取当前登录用户
  me: User
  
  # 获取文章列表
  posts(
    filter: PostFilterInput
    pagination: PaginationInput
    sort: SortInput
  ): PostConnection!
  
  # 获取单个文章
  post(id: ID, slug: String): Post
  
  # 获取标签列表
  tags: [Tag!]!
  
  # 获取评论
  comments(postId: ID!): [Comment!]!
}

# 连接类型(用于分页)
type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type PostEdge {
  node: Post!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

# ===== Mutation(变更) =====
type Mutation {
  # 用户相关
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
  
  # 文章相关
  createPost(input: CreatePostInput!): Post!
  updatePost(id: ID!, input: UpdatePostInput!): Post!
  deletePost(id: ID!): Boolean!
  publishPost(id: ID!): Post!
  unpublishPost(id: ID!): Post!
  
  # 评论相关
  createComment(postId: ID!, input: CreateCommentInput!): Comment!
  deleteComment(id: ID!): Boolean!
  
  # 点赞相关
  likePost(postId: ID!): Like!
  unlikePost(postId: ID!): Boolean!
}

# ===== Subscription(订阅) =====
type Subscription {
  # 实时订阅新评论
  commentAdded(postId: ID!): Comment!
  
  # 订阅文章更新
  postUpdated(id: ID!): Post!
  
  # 订阅用户状态
  userStatusChanged(userId: ID!): UserStatus!
}

二、Node.js + Apollo Server 实战

2.1 项目初始化

# ===== 项目初始化 =====

mkdir graphql-server
cd graphql-server

npm init -y

# 安装依赖
npm install @apollo/server graphql graphql-tag
npm install @as-integrations/fastify  # 如果使用 Fastify
npm install express @apollo/server/express4  # 如果使用 Express
npm install @graphql-tools/schema graphql-middleware  # 工具
npm install @prisma/client prisma  # 数据库 ORM
npm install @graphql-auth-directive  # 认证
npm install graphql-scalars  # 扩展标量类型

# 开发依赖
npm install -D typescript @types/node ts-node nodemon
// package.json
{
  "name": "graphql-server",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "nodemon --exec ts-node-esm server.ts",
    "build": "tsc",
    "start": "node dist/server.js",
    "prisma:generate": "prisma generate",
    "prisma:migrate": "prisma migrate dev"
  }
}

2.2 TypeScript 配置

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2.3 Schema 定义

// src/schema/index.ts
import { gql } from 'graphql-tag';

export const typeDefs = gql`
  scalar DateTime

  type User {
    id: ID!
    name: String!
    email: String!
    avatar: String
    bio: String
    role: Role!
    isActive: Boolean!
    createdAt: DateTime!
    updatedAt: DateTime!
    posts: [Post!]!
    postCount: Int!
  }

  type Post {
    id: ID!
    title: String!
    slug: String!
    content: String!
    excerpt: String
    coverImage: String
    published: Boolean!
    publishedAt: DateTime
    viewCount: Int!
    readTime: Int!
    createdAt: DateTime!
    updatedAt: DateTime!
    author: User!
    comments: [Comment!]!
    commentCount: Int!
    tags: [Tag!]!
    isLiked: Boolean!
    likeCount: Int!
  }

  type Comment {
    id: ID!
    content: String!
    createdAt: DateTime!
    author: User!
    post: Post!
    replies: [Comment!]!
    parent: Comment
  }

  type Tag {
    id: ID!
    name: String!
    slug: String!
    color: String
    postCount: Int!
  }

  type Like {
    id: ID!
    createdAt: DateTime!
    user: User!
    post: Post!
  }

  type AuthPayload {
    token: String!
    user: User!
  }

  enum Role {
    ADMIN
    EDITOR
    AUTHOR
    READER
  }

  type Query {
    # 用户
    me: User
    user(id: ID!): User
    users(pagination: PaginationInput): UserConnection!

    # 文章
    post(id: ID, slug: String): Post
    posts(
      filter: PostFilterInput
      pagination: PaginationInput
      sort: SortInput
    ): PostConnection!
    featuredPosts: [Post!]!

    # 标签
    tags: [Tag!]!
    tag(slug: String!): Tag

    # 评论
    comments(postId: ID!): [Comment!]!
  }

  type Mutation {
    # 认证
    login(email: String!, password: String!): AuthPayload!
    register(input: RegisterInput!): AuthPayload!

    # 用户
    updateProfile(input: UpdateProfileInput!): User!

    # 文章
    createPost(input: CreatePostInput!): Post!
    updatePost(id: ID!, input: UpdatePostInput!): Post!
    deletePost(id: ID!): Boolean!
    publishPost(id: ID!): Post!
    unpublishPost(id: ID!): Post!

    # 评论
    createComment(postId: ID!, content: String!, parentId: ID): Comment!
    deleteComment(id: ID!): Boolean!

    # 点赞
    likePost(postId: ID!): Like!
    unlikePost(postId: ID!): Boolean!
  }

  type Subscription {
    commentAdded(postId: ID!): Comment!
    postLiked(postId: ID!): Like!
    postViewed(postId: ID!): Post!
  }

  # 输入类型
  input RegisterInput {
    name: String!
    email: String!
    password: String!
  }

  input UpdateProfileInput {
    name: String
    avatar: String
    bio: String
  }

  input CreatePostInput {
    title: String!
    content: String!
    slug: String
    coverImage: String
    tagIds: [ID!]
  }

  input UpdatePostInput {
    title: String
    content: String
    coverImage: String
    tagIds: [ID!]
  }

  input PostFilterInput {
    search: String
    tagSlugs: [String!]
    authorId: ID
    published: Boolean
    fromDate: DateTime
    toDate: DateTime
  }

  input PaginationInput {
    page: Int = 1
    limit: Int = 10
  }

  input SortInput {
    field: String = "createdAt"
    order: SortOrder = DESC
  }

  enum SortOrder {
    ASC
    DESC
  }

  # 连接类型
  type UserConnection {
    edges: [UserEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
  }

  type UserEdge {
    node: User!
    cursor: String!
  }

  type PostConnection {
    edges: [PostEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
  }

  type PostEdge {
    node: Post!
    cursor: String!
  }

  type PageInfo {
    hasNextPage: Boolean!
    hasPreviousPage: Boolean!
    startCursor: String
    endCursor: String
  }
`;

2.4 Resolver 函数

// src/resolvers/index.ts
import { Context } from '../context';
import { AuthenticationError, ForbiddenError, UserInputError } from '../errors';
import {prisma} from '../lib/prisma';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

export const resolvers = {
  // 标量类型解析
  DateTime: {
    __parseValue(value: string) {
      return new Date(value);
    },
    __serialize(value: Date) {
      return value.toISOString();
    },
    __parseLiteral(ast: any) {
      if (ast.kind === 'StringValue') {
        return new Date(ast.value);
      }
      return null;
    },
  },

  // 查询解析器
  Query: {
    // 当前用户
    me: async (_: any, __: any, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }
      return context.user;
    },

    // 单个用户
    user: async (_: any, { id }: { id: string }, context: Context) => {
      return prisma.user.findUnique({ where: { id } });
    },

    // 用户列表
    users: async (_: any, { pagination }: { pagination: any }, context: Context) => {
      const { page = 1, limit = 10 } = pagination || {};
      const skip = (page - 1) * limit;

      const [users, totalCount] = await Promise.all([
        prisma.user.findMany({
          skip,
          take: limit,
          orderBy: { createdAt: 'desc' },
        }),
        prisma.user.count(),
      ]);

      return {
        edges: users.map((user) => ({ node: user, cursor: Buffer.from(user.id).toString('base64') })),
        pageInfo: {
          hasNextPage: skip + users.length < totalCount,
          hasPreviousPage: page > 1,
        },
        totalCount,
      };
    },

    // 文章
    post: async (_: any, { id, slug }: { id?: string; slug?: string }, context: Context) => {
      return prisma.post.findFirst({
        where: id ? { id } : { slug },
      });
    },

    // 文章列表
    posts: async (_: any, { filter, pagination, sort }: any, context: Context) => {
      const { page = 1, limit = 10 } = pagination || {};
      const { field = 'createdAt', order = 'desc' } = sort || {};
      const skip = (page - 1) * limit;

      // 构建查询条件
      const where: any = {};
      
      if (filter) {
        if (filter.search) {
          where.OR = [
            { title: { contains: filter.search, mode: 'insensitive' } },
            { content: { contains: filter.search, mode: 'insensitive' } },
          ];
        }
        if (filter.tagSlugs) {
          where.tags = {
            some: { slug: { in: filter.tagSlugs } },
          };
        }
        if (filter.authorId) {
          where.authorId = filter.authorId;
        }
        if (filter.published !== undefined) {
          where.published = filter.published;
        }
        if (filter.fromDate) {
          where.createdAt = { ...where.createdAt, gte: new Date(filter.fromDate) };
        }
        if (filter.toDate) {
          where.createdAt = { ...where.createdAt, lte: new Date(filter.toDate) };
        }
      }

      const [posts, totalCount] = await Promise.all([
        prisma.post.findMany({
          where,
          skip,
          take: limit,
          orderBy: { [field]: order },
          include: {
            author: true,
            tags: true,
            _count: { select: { comments: true, likes: true } },
          },
        }),
        prisma.post.count({ where }),
      ]);

      // 判断是否点赞
      const postsWithLikeStatus = posts.map((post) => ({
        ...post,
        isLiked: context.user ? await checkIsLiked(post.id, context.user.id) : false,
      }));

      return {
        edges: postsWithLikeStatus.map((post) => ({
          node: post,
          cursor: Buffer.from(post.id).toString('base64'),
        })),
        pageInfo: {
          hasNextPage: skip + posts.length < totalCount,
          hasPreviousPage: page > 1,
          startCursor: posts[0] ? Buffer.from(posts[0].id).toString('base64') : null,
          endCursor: posts[posts.length - 1] ? Buffer.from(posts[posts.length - 1].id).toString('base64') : null,
        },
        totalCount,
      };
    },

    // 精选文章
    featuredPosts: async (_: any, __: any, context: Context) => {
      return prisma.post.findMany({
        where: { published: true },
        orderBy: { viewCount: 'desc' },
        take: 5,
        include: { author: true, tags: true },
      });
    },

    // 标签列表
    tags: async (_: any, __: any, context: Context) => {
      return prisma.tag.findMany({
        include: { _count: { select: { posts: true } } },
      });
    },

    // 评论列表
    comments: async (_: any, { postId }: { postId: string }, context: Context) => {
      return prisma.comment.findMany({
        where: { postId, parentId: null },
        include: {
          author: true,
          replies: {
            include: { author: true, replies: { include: { author: true } } },
          },
        },
        orderBy: { createdAt: 'desc' },
      });
    },
  },

  // 变更解析器
  Mutation: {
    // 登录
    login: async (_: any, { email, password }: { email: string; password: string }) => {
      const user = await prisma.user.findUnique({ where: { email } });
      
      if (!user || !await bcrypt.compare(password, user.passwordHash)) {
        throw new AuthenticationError('邮箱或密码错误');
      }

      const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET!, {
        expiresIn: '7d',
      });

      return { token, user };
    },

    // 注册
    register: async (_: any, { input }: { input: any }) => {
      const existingUser = await prisma.user.findUnique({
        where: { email: input.email },
      });

      if (existingUser) {
        throw new UserInputError('该邮箱已被注册');
      }

      const passwordHash = await bcrypt.hash(input.password, 10);

      const user = await prisma.user.create({
        data: {
          name: input.name,
          email: input.email,
          passwordHash,
          role: 'AUTHOR',
        },
      });

      const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET!, {
        expiresIn: '7d',
      });

      return { token, user };
    },

    // 创建文章
    createPost: async (_: any, { input }: { input: any }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const slug = input.slug || generateSlug(input.title);

      const post = await prisma.post.create({
        data: {
          title: input.title,
          slug,
          content: input.content,
          coverImage: input.coverImage,
          authorId: context.user.id,
          published: false,
        },
        include: { author: true, tags: true },
      });

      // 添加标签
      if (input.tagIds && input.tagIds.length > 0) {
        await prisma.post.update({
          where: { id: post.id },
          data: {
            tags: { connect: input.tagIds.map((id: string) => ({ id })) },
          },
        });
      }

      return post;
    },

    // 更新文章
    updatePost: async (_: any, { id, input }: { id: string; input: any }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const post = await prisma.post.findUnique({ where: { id } });

      if (!post) {
        throw new UserInputError('文章不存在');
      }

      if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
        throw new ForbiddenError('无权限修改此文章');
      }

      const updatedPost = await prisma.post.update({
        where: { id },
        data: {
          title: input.title,
          content: input.content,
          coverImage: input.coverImage,
        },
        include: { author: true, tags: true },
      });

      // 更新标签
      if (input.tagIds) {
        await prisma.post.update({
          where: { id },
          data: {
            tags: { set: input.tagIds.map((id: string) => ({ id })) },
          },
        });
      }

      return updatedPost;
    },

    // 删除文章
    deletePost: async (_: any, { id }: { id: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const post = await prisma.post.findUnique({ where: { id } });

      if (!post) {
        throw new UserInputError('文章不存在');
      }

      if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
        throw new ForbiddenError('无权限删除此文章');
      }

      await prisma.post.delete({ where: { id } });
      return true;
    },

    // 发布文章
    publishPost: async (_: any, { id }: { id: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      return prisma.post.update({
        where: { id },
        data: { published: true, publishedAt: new Date() },
        include: { author: true, tags: true },
      });
    },

    // 创建评论
    createComment: async (_: any, { postId, content, parentId }: any, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const comment = await prisma.comment.create({
        data: {
          content,
          postId,
          authorId: context.user.id,
          parentId,
        },
        include: { author: true, post: true },
      });

      return comment;
    },

    // 点赞
    likePost: async (_: any, { postId }: { postId: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      const existing = await prisma.like.findFirst({
        where: { postId, userId: context.user.id },
      });

      if (existing) {
        return existing;
      }

      return prisma.like.create({
        data: { postId, userId: context.user.id },
        include: { user: true, post: true },
      });
    },

    // 取消点赞
    unlikePost: async (_: any, { postId }: { postId: string }, context: Context) => {
      if (!context.user) {
        throw new AuthenticationError('请先登录');
      }

      await prisma.like.deleteMany({
        where: { postId, userId: context.user.id },
      });

      return true;
    },
  },

  // 订阅解析器
  Subscription: {
    commentAdded: {
      subscribe: async function* (_, { postId }: any) {
        for await (const comment of commentIterator(postId)) {
          yield { commentAdded: comment };
        }
      },
    },
  },

  // 类型解析器
  User: {
    posts: async (parent: any) => {
      return prisma.post.findMany({
        where: { authorId: parent.id, published: true },
        orderBy: { createdAt: 'desc' },
      });
    },
    postCount: async (parent: any) => {
      return prisma.post.count({ where: { authorId: parent.id, published: true } });
    },
  },

  Post: {
    author: async (parent: any) => {
      return prisma.user.findUnique({ where: { id: parent.authorId } });
    },
    comments: async (parent: any) => {
      return prisma.comment.findMany({
        where: { postId: parent.id, parentId: null },
        orderBy: { createdAt: 'desc' },
      });
    },
    commentCount: async (parent: any) => {
      return prisma.comment.count({ where: { postId: parent.id } });
    },
    tags: async (parent: any) => {
      return prisma.tag.findMany({
        where: { posts: { some: { id: parent.id } } },
      });
    },
    likeCount: async (parent: any) => {
      return prisma.like.count({ where: { postId: parent.id } });
    },
    readTime: (parent: any) => {
      const wordsPerMinute = 200;
      const wordCount = parent.content.split(/\s+/).length;
      return Math.ceil(wordCount / wordsPerMinute);
    },
  },

  Tag: {
    postCount: async (parent: any) => {
      return prisma.post.count({
        where: { published: true, tags: { some: { id: parent.id } } },
      });
    },
  },
};

// 辅助函数
async function checkIsLiked(postId: string, userId: string): Promise<boolean> {
  const like = await prisma.like.findFirst({
    where: { postId, userId },
  });
  return !!like;
}

function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '');
}

async function* commentIterator(postId: string) {
  // 实现 PubSub 逻辑
}

2.5 Context 与认证

// src/context.ts
import { PrismaClient } from '@prisma/client';
import { User } from '@prisma/client';
import jwt from 'jsonwebtoken';

export interface Context {
  prisma: PrismaClient;
  user: User | null;
}

export async function createContext(req: any): Promise<Context> {
  const prisma = new PrismaClient();

  // 从 Authorization Header 获取 token
  const authHeader = req.headers.authorization || '';
  const token = authHeader.replace('Bearer ', '');

  let user = null;

  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string };
      user = await prisma.user.findUnique({ where: { id: decoded.userId } });
    } catch (error) {
      // token 无效,继续以游客身份
    }
  }

  return { prisma, user };
}

2.6 服务器入口

// src/server.ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import cors from 'cors';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
import { createContext } from './context';

const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true, // 开发环境开启
  formatError: (error) => {
    // 生产环境移除 stack trace
    if (process.env.NODE_ENV === 'production') {
      return {
        message: error.message,
        path: error.path,
      };
    }
    return error;
  },
});

await server.start();

app.use(
  '/graphql',
  cors<cors.CorsRequest>(),
  express.json({ limit: '10mb' }),
  expressMiddleware(server, {
    context: async ({ req }) => createContext(req),
  })
);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
  console.log(`🚀 GraphQL Server ready at http://localhost:${PORT}/graphql`);
});

三、Prisma 数据库集成

3.1 Prisma Schema

// prisma/schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id           String    @id @default(cuid())
  email        String    @unique
  name         String
  passwordHash String
  avatar       String?
  bio          String?
  role         Role      @default(AUTHOR)
  isActive     Boolean   @default(true)
  createdAt    DateTime  @default(now())
  updatedAt    DateTime  @updatedAt

  posts    Post[]
  comments Comment[]
  likes    Like[]
}

model Post {
  id          String    @id @default(cuid())
  title       String
  slug        String    @unique
  content     String
  excerpt     String?
  coverImage  String?
  published   Boolean   @default(false)
  publishedAt DateTime?
  viewCount   Int       @default(0)
  readTime    Int       @default(0)
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt

  authorId String
  author   User   @relation(fields: [authorId], references: [id])

  tags     Tag[]
  comments Comment[]
  likes    Like[]

  @@index([authorId])
  @@index([published])
  @@index([slug])
}

model Tag {
  id        String   @id @default(cuid())
  name      String
  slug      String   @unique
  color     String?
  createdAt DateTime @default(now())

  posts Post[]
}

model Comment {
  id        String   @id @default(cuid())
  content   String
  createdAt DateTime @default(now())

  postId String
  post   Post   @relation(fields: [postId], references: [id], onDelete: Cascade)

  authorId String
  author   User   @relation(fields: [authorId], references: [id])

  parentId String?
  parent   Comment?  @relation("CommentReplies", fields: [parentId], references: [id])
  replies  Comment[] @relation("CommentReplies")

  @@index([postId])
  @@index([authorId])
}

model Like {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now())

  postId String
  post   Post   @relation(fields: [postId], references: [id], onDelete: Cascade)

  userId String
  user   User   @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([postId, userId])
}

enum Role {
  ADMIN
  EDITOR
  AUTHOR
  READER
}

3.2 Prisma 客户端

// src/lib/prisma.ts
import { PrismaClient } from '@prisma/client';

declare global {
  var __prisma: PrismaClient | undefined;
}

export const prisma =
  global.__prisma ||
  new PrismaClient({
    log: process.env.NODE_ENV === 'development'
      ? ['query', 'error', 'warn']
      : ['error'],
  });

if (process.env.NODE_ENV !== 'production') {
  global.__prisma = prisma;
}

四、前端集成(React + Apollo Client)

4.1 Apollo Client 配置

// src/lib/apollo-client.ts
import { ApolloClient, InMemoryCache, createHttpLink, from } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { createClient } from 'graphql-ws';

const httpLink = createHttpLink({
  uri: process.env.NEXT_PUBLIC_GRAPHQL_URL || 'http://localhost:4000/graphql',
});

// Auth Link
const authLink = setContext((_, { headers }) => {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

// Error Link
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) => {
      console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
      
      if (message === '请先登录') {
        // 处理未登录
        localStorage.removeItem('token');
        window.location.href = '/login';
      }
    });
  }

  if (networkError) {
    console.error(`[Network error]: ${networkError}`);
  }
});

// Subscription Link (WebSocket)
const wsLink = typeof window !== 'undefined'
  ? new GraphQLWsLink(
      createClient({
        url: process.env.NEXT_PUBLIC_GRAPHQL_WS_URL || 'ws://localhost:4000/graphql',
        connectionParams: () => ({
          Authorization: localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : '',
        }),
      })
    )
  : null;

// Split Link
const splitLink = typeof window !== 'undefined' && wsLink
  ? split(({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      );
    }, wsLink, authLink.concat(httpLink))
  : authLink.concat(httpLink);

// Cache
const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        posts: {
          keyArgs: ['filter'],
          merge(existing, incoming, { args }) {
            if (!args?.pagination?.page || args.pagination.page === 1) {
              return incoming;
            }
            return {
              ...incoming,
              edges: [...(existing?.edges || []), ...incoming.edges],
            };
          },
        },
      },
    },
    Post: {
      fields: {
        isLiked: {
          merge(_, incoming) {
            return incoming;
          },
        },
        likeCount: {
          merge(_, incoming) {
            return incoming;
          },
        },
      },
    },
  },
});

export const apolloClient = new ApolloClient({
  link: from([errorLink, splitLink]),
  cache,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
  },
});

4.2 React Hooks 封装

// src/hooks/useGraphQL.ts
import { useQuery, useMutation, useSubscription } from '@apollo/client';
import { gql } from '@apollo/client';

// ===== 查询 Hooks =====

// 获取文章列表
export function usePosts(filter?: any, pagination?: any, sort?: any) {
  return useQuery(GET_POSTS, {
    variables: { filter, pagination, sort },
    notifyOnNetworkStatusChange: true,
  });
}

// 获取单篇文章
export function usePost(id?: string, slug?: string) {
  return useQuery(GET_POST, {
    variables: { id, slug },
    skip: !id && !slug,
  });
}

// 获取当前用户
export function useCurrentUser() {
  return useQuery(GET_CURRENT_USER);
}

// 获取标签列表
export function useTags() {
  return useQuery(GET_TAGS);
}

// ===== 变更 Hooks =====

// 登录
export function useLogin() {
  return useMutation(LOGIN, {
    onCompleted: (data) => {
      localStorage.setItem('token', data.login.token);
    },
  });
}

// 注册
export function useRegister() {
  return useMutation(REGISTER, {
    onCompleted: (data) => {
      localStorage.setItem('token', data.register.token);
    },
  });
}

// 创建文章
export function useCreatePost() {
  return useMutation(CREATE_POST, {
    refetchQueries: [{ query: GET_POSTS }],
  });
}

// 更新文章
export function useUpdatePost() {
  return useMutation(UPDATE_POST, {
    refetchQueries: [{ query: GET_POSTS }, { query: GET_POST }],
  });
}

// 点赞
export function useLikePost() {
  return useMutation(LIKE_POST, {
    optimisticResponse: {
      likePost: {
        __typename: 'Like',
        id: 'temp-id',
      },
    },
    update: (cache, { data: { likePost } }) => {
      // 更新缓存
    },
  });
}

// ===== 订阅 Hooks =====

// 订阅新评论
export function useCommentSubscription(postId: string) {
  return useSubscription(COMMENT_SUBSCRIPTION, {
    variables: { postId },
  });
}

// ===== GraphQL 文档 =====

const GET_POSTS = gql`
  query GetPosts($filter: PostFilterInput, $pagination: PaginationInput, $sort: SortInput) {
    posts(filter: $filter, pagination: $pagination, sort: $sort) {
      edges {
        node {
          id
          title
          slug
          excerpt
          coverImage
          published
          viewCount
          readTime
          createdAt
          author {
            id
            name
            avatar
          }
          tags {
            id
            name
            slug
          }
          commentCount
          likeCount
          isLiked
        }
      }
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
      totalCount
    }
  }
`;

const GET_POST = gql`
  query GetPost($id: ID, $slug: String) {
    post(id: $id, slug: $slug) {
      id
      title
      slug
      content
      excerpt
      coverImage
      published
      publishedAt
      viewCount
      readTime
      createdAt
      author {
        id
        name
        avatar
        bio
      }
      tags {
        id
        name
        slug
        color
      }
      comments {
        id
        content
        createdAt
        author {
          id
          name
          avatar
        }
        replies {
          id
          content
          createdAt
          author {
            id
            name
            avatar
          }
        }
      }
      commentCount
      likeCount
      isLiked
    }
  }
`;

const GET_CURRENT_USER = gql`
  query GetCurrentUser {
    me {
      id
      name
      email
      avatar
      bio
      role
    }
  }
`;

const GET_TAGS = gql`
  query GetTags {
    tags {
      id
      name
      slug
      color
      postCount
    }
  }
`;

const LOGIN = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
      user {
        id
        name
        email
      }
    }
  }
`;

const REGISTER = gql`
  mutation Register($input: RegisterInput!) {
    register(input: $input) {
      token
      user {
        id
        name
        email
      }
    }
  }
`;

const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      id
      title
      slug
    }
  }
`;

const UPDATE_POST = gql`
  mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
    updatePost(id: $id, input: $input) {
      id
      title
      slug
      content
    }
  }
`;

const LIKE_POST = gql`
  mutation LikePost($postId: ID!) {
    likePost(postId: $postId) {
      id
      post {
        id
        likeCount
      }
    }
  }
`;

const COMMENT_SUBSCRIPTION = gql`
  subscription CommentAdded($postId: ID!) {
    commentAdded(postId: $postId) {
      id
      content
      createdAt
      author {
        id
        name
        avatar
      }
    }
  }
`;

4.3 React 组件示例

// src/components/PostList.tsx
import { usePosts } from '@/hooks/useGraphQL';
import { Link } from 'next/link';
import { useRouter } from 'next/navigation';

export function PostList() {
  const router = useRouter();
  const { data, loading, error, fetchMore } = usePosts(
    { published: true },
    { page: 1, limit: 10 },
    { field: 'createdAt', order: 'DESC' }
  );

  if (loading && !data) return <PostListSkeleton />;
  if (error) return <ErrorMessage error={error} />;

  const { posts } = data;
  const { edges, pageInfo, totalCount } = posts;

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">文章列表</h1>
        <span className="text-gray-500">共 {totalCount} 篇</span>
      </div>

      <div className="grid gap-6">
        {edges.map(({ node: post }: any) => (
          <PostCard key={post.id} post={post} />
        ))}
      </div>

      {pageInfo.hasNextPage && (
        <div className="text-center mt-8">
          <button
            onClick={() => {
              fetchMore({
                variables: {
                  pagination: { page: Math.ceil(edges.length / 10) + 1, limit: 10 },
                },
              });
            }}
            disabled={loading}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {loading ? '加载中...' : '加载更多'}
          </button>
        </div>
      )}
    </div>
  );
}

function PostCard({ post }: { post: any }) {
  return (
    <article className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition">
      {post.coverImage && (
        <img
          src={post.coverImage}
          alt={post.title}
          className="w-full h-48 object-cover"
        />
      )}
      
      <div className="p-6">
        <div className="flex gap-2 mb-3">
          {post.tags.map((tag: any) => (
            <Link
              key={tag.id}
              href={`/tags/${tag.slug}`}
              className="px-2 py-1 text-xs bg-gray-100 rounded-full hover:bg-gray-200"
            >
              {tag.name}
            </Link>
          ))}
        </div>
        
        <Link href={`/posts/${post.slug}`}>
          <h2 className="text-xl font-bold mb-2 hover:text-blue-600">
            {post.title}
          </h2>
        </Link>
        
        {post.excerpt && (
          <p className="text-gray-600 mb-4 line-clamp-2">{post.excerpt}</p>
        )}
        
        <div className="flex items-center justify-between text-sm text-gray-500">
          <div className="flex items-center gap-2">
            <img
              src={post.author.avatar || '/default-avatar.png'}
              alt={post.author.name}
              className="w-6 h-6 rounded-full"
            />
            <span>{post.author.name}</span>
          </div>
          
          <div className="flex items-center gap-4">
            <span>{new Date(post.createdAt).toLocaleDateString()}</span>
            <span>{post.readTime} 分钟阅读</span>
            <span>{post.likeCount} 点赞</span>
            <span>{post.commentCount} 评论</span>
          </div>
        </div>
      </div>
    </article>
  );
}
// src/components/CreatePostForm.tsx
'use client';

import { useState } from 'react';
import { useCreatePost, useTags } from '@/hooks/useGraphQL';
import { useRouter } from 'next/navigation';

export function CreatePostForm() {
  const router = useRouter();
  const [createPost, { loading }] = useCreatePost();
  const { data: tagsData } = useTags();
  
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    coverImage: '',
    tagIds: [] as string[],
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const { data } = await createPost({
        variables: { input: formData },
      });
      
      router.push(`/posts/${data.createPost.slug}`);
    } catch (error) {
      console.error('创建文章失败:', error);
    }
  };

  const handleTagChange = (tagId: string) => {
    setFormData((prev) => ({
      ...prev,
      tagIds: prev.tagIds.includes(tagId)
        ? prev.tagIds.filter((id) => id !== tagId)
        : [...prev.tagIds, tagId],
    }));
  };

  return (
    <form onSubmit={handleSubmit} className="max-w-2xl mx-auto space-y-6">
      <div>
        <label htmlFor="title" className="block mb-2 font-medium">
          标题
        </label>
        <input
          type="text"
          id="title"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg"
          required
        />
      </div>

      <div>
        <label htmlFor="content" className="block mb-2 font-medium">
          内容
        </label>
        <textarea
          id="content"
          value={formData.content}
          onChange={(e) => setFormData({ ...formData, content: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg min-h-[300px]"
          required
        />
      </div>

      <div>
        <label htmlFor="coverImage" className="block mb-2 font-medium">
          封面图片 URL
        </label>
        <input
          type="url"
          id="coverImage"
          value={formData.coverImage}
          onChange={(e) => setFormData({ ...formData, coverImage: e.target.value })}
          className="w-full px-4 py-2 border rounded-lg"
          placeholder="https://..."
        />
      </div>

      <div>
        <label className="block mb-2 font-medium">标签</label>
        <div className="flex flex-wrap gap-2">
          {tagsData?.tags?.map((tag: any) => (
            <button
              key={tag.id}
              type="button"
              onClick={() => handleTagChange(tag.id)}
              className={`px-3 py-1 rounded-full text-sm ${
                formData.tagIds.includes(tag.id)
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 hover:bg-gray-200'
              }`}
            >
              {tag.name}
            </button>
          ))}
        </div>
      </div>

      <button
        type="submit"
        disabled={loading}
        className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
      >
        {loading ? '创建中...' : '创建文章'}
      </button>
    </form>
  );
}

五、数据加载器(DataLoader)

5.1 N+1 问题与解决

// src/loaders/index.ts
import DataLoader from 'dataloader';
import { prisma } from '../lib/prisma';

// 用户数据加载器
export const createUserLoader = () =>
  new DataLoader<string, any>(async (ids) => {
    const users = await prisma.user.findMany({
      where: { id: { in: ids } },
    });
    
    const userMap = new Map(users.map((user) => [user.id, user]));
    
    return ids.map((id) => userMap.get(id) || null);
  });

// 文章数据加载器
export const createPostLoader = () =>
  new DataLoader<string, any>(async (ids) => {
    const posts = await prisma.post.findMany({
      where: { id: { in: ids } },
      include: { author: true, tags: true },
    });
    
    const postMap = new Map(posts.map((post) => [post.id, post]));
    
    return ids.map((id) => postMap.get(id) || null);
  });

// 评论数量加载器
export const createCommentCountLoader = () =>
  new DataLoader<string, number>(async (postIds) => {
    const counts = await prisma.comment.groupBy({
      by: ['postId'],
      _count: { postId: true },
      where: { postId: { in: postIds } },
    });
    
    const countMap = new Map(counts.map((c) => [c.postId, c._count.postId]));
    
    return postIds.map((id) => countMap.get(id) || 0);
  });

// 点赞数量加载器
export const createLikeCountLoader = () =>
  new DataLoader<string, number>(async (postIds) => {
    const counts = await prisma.like.groupBy({
      by: ['postId'],
      _count: { postId: true },
      where: { postId: { in: postIds } },
    });
    
    const countMap = new Map(counts.map((c) => [c.postId, c._count.postId]));
    
    return postIds.map((id) => countMap.get(id) || 0);
  });
// 在 Context 中注入 Loader
// src/context.ts

import { PrismaClient } from '@prisma/client';
import { createUserLoader, createPostLoader } from './loaders';

export interface Context {
  prisma: PrismaClient;
  user: User | null;
  loaders: {
    user: ReturnType<typeof createUserLoader>;
    post: ReturnType<typeof createPostLoader>;
  };
}

export async function createContext(req: any): Promise<Context> {
  const prisma = new PrismaClient();
  
  // ... 认证逻辑 ...
  
  return {
    prisma,
    user,
    loaders: {
      user: createUserLoader(),
      post: createPostLoader(),
    },
  };
}

5.2 在 Resolver 中使用 Loader

// src/resolvers/post.ts

export const Post = {
  author: async (parent: any, _: any, { loaders }: Context) => {
    // 使用 DataLoader 批量加载
    return loaders.user.load(parent.authorId);
  },
  
  commentCount: async (parent: any, _: any, { loaders }: Context) => {
    return loaders.commentCount.load(parent.id);
  },
  
  likeCount: async (parent: any, _: any, { loaders }: Context) => {
    return loaders.likeCount.load(parent.id);
  },
};

六、中间件与权限控制

6.1 GraphQL 中间件

// src/middleware/authorization.ts
import { AuthenticationError, ForbiddenError } from '../errors';

// 检查是否登录
export function requireAuth(resolver: any) {
  return (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    return resolver(root, args, context, info);
  };
}

// 检查管理员权限
export function requireAdmin(resolver: any) {
  return (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    if (context.user.role !== 'ADMIN') {
      throw new ForbiddenError('需要管理员权限');
    }
    return resolver(root, args, context, info);
  };
}

// 检查文章所有权
export function requirePostOwner(resolver: any) {
  return async (root: any, args: any, context: Context, info: any) => {
    if (!context.user) {
      throw new AuthenticationError('请先登录');
    }
    
    const post = await context.prisma.post.findUnique({
      where: { id: args.id },
    });
    
    if (!post) {
      throw new UserInputError('文章不存在');
    }
    
    if (post.authorId !== context.user.id && context.user.role !== 'ADMIN') {
      throw new ForbiddenError('无权限修改此文章');
    }
    
    return resolver(root, args, context, info);
  };
}

// 字段级中间件示例
export const fieldMiddleware = {
  Mutation: {
    // 所有 Mutation 需要登录
    '*': requireAuth,
    
    // 例外情况
    login: (resolver) => resolver,
    register: (resolver) => resolver,
  },
};

6.2 Schema 指令(Directive)

# src/directives/auth.graphql

# 认证指令
directive @auth on FIELD_DEFINITION | OBJECT

# 管理员指令
directive @admin on FIELD_DEFINITION | OBJECT

# 速率限制指令
directive @rateLimit(max: Int!, window: String!) on FIELD_DEFINITION

# 弃用指令(内置)
directive @deprecated(reason: String) on FIELD_DEFINITION | ENUM_VALUE

# 使用示例
type Query {
  # 公开查询
  posts: [Post!]!
  
  # 需要登录
  me: User @auth
  
  # 需要管理员
  users: [User!]! @admin
}

type Mutation {
  # 需要登录
  createPost(input: CreatePostInput!): Post! @auth
  
  # 速率限制
  login(email: String!, password: String!): AuthPayload! @rateLimit(max: 5, window: "5m")
}

七、性能优化

7.1 查询复杂度限制

// src/utils/queryComplexity.ts
import { createComplexityLimitRule } from 'graphql-query-complexity';
import { specifiedRules, validate } from 'graphql';
import { GraphQLError } from 'graphql';

const complexityRule = createComplexityLimitRule(1000, {
  onCost: (cost) => {
    console.log(`Query cost: ${cost}`);
  },
  formatErrorErrorMessage: (cost) => {
    return `Query cost ${cost} exceeds maximum allowed cost of 1000`;
  },
  formatError: (error) => {
    return new GraphQLError(
      'Your query is too complex. Please simplify it.',
      undefined,
      undefined,
      undefined,
      undefined,
      error
    );
  },
});

export { complexityRule };

7.2 响应缓存

// src/middleware/responseCache.ts
import { responseCachePlugin } from '@apollo/server-plugin-response-cache';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    responseCachePlugin({
      sessionId: (requestContext) => {
        // 基于用户 ID 缓存
        return requestContext.context.user?.id || 'anonymous';
      },
    }),
  ],
});

// 或者使用 Redis 缓存
import RedisStore from 'apollo-server-plugin-response-cache-redis';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    responseCachePlugin({
      store: new RedisStore({
        redis: new Redis(process.env.REDIS_URL),
        ttl: 60 * 60, // 1 hour
      }),
    }),
  ],
});

7.3 Persisted Queries

// 客户端:使用 APQ (Automatic Persisted Queries)
import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from '@apollo/client';
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries';
import { sha256 } from 'crypto-hash';

const persistedQueriesLink = createPersistedQueryLink({ sha256 });

const client = new ApolloClient({
  link: ApolloLink.from([
    persistedQueriesLink,
    new HttpLink({ uri: '/graphql' }),
  ]),
  cache: new InMemoryCache(),
});

八、实战:完整的 GraphQL API

8.1 项目结构

graphql-api/
├── src/
│   ├── schema/
│   │   ├── index.ts          # 类型定义
│   │   ├── typeDefs/         # 分类型定义
│   │   │   ├── user.ts
│   │   │   ├── post.ts
│   │   │   ├── comment.ts
│   │   │   └── common.ts
│   │   └── directives/       # 自定义指令
│   │       └── auth.ts
│   ├── resolvers/
│   │   ├── index.ts          # 解析器入口
│   │   ├── Query/            # 查询解析器
│   │   ├── Mutation/         # 变更解析器
│   │   ├── Subscription/     # 订阅解析器
│   │   └── types/            # 类型解析器
│   ├── context.ts
│   ├── errors.ts
│   ├── loaders/              # DataLoader
│   ├── middleware/           # 中间件
│   ├── lib/
│   │   ├── prisma.ts
│   │   ├── redis.ts
│   │   └── utils.ts
│   └── server.ts
├── prisma/
│   └── schema.prisma
├── tests/
└── package.json

8.2 完整服务器代码

// src/server.ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import express from 'express';
import cors from 'cors';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
import { createContext, Context } from './context';
import { complexityRule } from './utils/queryComplexity';
import { responseCachePlugin } from './apollo-server-plugin-response-cache';

async function main() {
  const app = express();

  const server = new ApolloServer<Context>({
    typeDefs,
    resolvers,
    introspection: process.env.NODE_ENV !== 'production',
    validationRules: [complexityRule],
    plugins: [
      ApolloServerPluginCacheControl({
        defaultMaxAge: 60, // 60 秒
        calculateHttpHeaders: true,
      }),
      ApolloServerPluginLandingPageLocalDefault({
        includeCookies: true,
      }),
      responseCachePlugin(),
    ],
  });

  await server.start();

  app.use(
    '/graphql',
    cors<cors.CorsRequest>({
      origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
      credentials: true,
    }),
    express.json({ limit: '10mb' }),
    expressMiddleware(server, {
      context: async ({ req }) => createContext(req),
      formatError: (error) => {
        // 生产环境错误处理
        if (process.env.NODE_ENV === 'production') {
          return {
            message: error.message,
            path: error.path,
          };
        }
        return error;
      },
    })
  );

  // 健康检查
  app.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
  });

  const PORT = process.env.PORT || 4000;

  app.listen(PORT, () => {
    console.log(`
🚀 GraphQL Server ready!
   📍 Local:      http://localhost:${PORT}/graphql
   📍 Studio:     http://studio.apollographql.com/sandbox
   🌐 Environment: ${process.env.NODE_ENV || 'development'}
    `);
  });
}

main().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});

九、测试

9.1 Jest 测试配置

// tests/setup.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

beforeAll(async () => {
  // 清理并填充测试数据
  await prisma.comment.deleteMany();
  await prisma.like.deleteMany();
  await prisma.post.deleteMany();
  await prisma.user.deleteMany();
  
  // 创建测试用户
  await prisma.user.create({
    data: {
      id: 'test-user-1',
      email: 'test@example.com',
      name: 'Test User',
      passwordHash: '$2a$10$...',
      role: 'AUTHOR',
    },
  });
});

afterAll(async () => {
  await prisma.$disconnect();
});

9.2 GraphQL 测试

// tests/graphql.test.ts
import { ApolloServer } from '@apollo/server';
import { typeDefs } from '../src/schema';
import { resolvers } from '../src/resolvers';
import { createContext } from '../src/context';

describe('GraphQL API', () => {
  let server: ApolloServer;
  let testContext: { prisma: PrismaClient; user: any };

  beforeAll(async () => {
    testContext = await createTestContext();
    server = new ApolloServer({
      typeDefs,
      resolvers,
    });
  });

  afterAll(async () => {
    await server.stop();
  });

  describe('Query', () => {
    it('should return posts', async () => {
      const query = `
        query GetPosts {
          posts {
            edges {
              node {
                id
                title
                author {
                  name
                }
              }
            }
          }
        }
      `;

      const response = await server.executeOperation(
        { query },
        { contextValue: testContext }
      );

      expect(response.body.kind).toBe('single');
      if (response.body.kind === 'single') {
        expect(response.body.singleResult.errors).toBeUndefined();
        expect(response.body.singleResult.data?.posts.edges).toBeDefined();
      }
    });
  });

  describe('Mutation', () => {
    it('should create a post', async () => {
      const mutation = `
        mutation CreatePost($input: CreatePostInput!) {
          createPost(input: $input) {
            id
            title
            slug
          }
        }
      `;

      const response = await server.executeOperation(
        {
          query: mutation,
          variables: {
            input: {
              title: 'Test Post',
              content: 'Test content',
            },
          },
        },
        { contextValue: testContext }
      );

      expect(response.body.kind).toBe('single');
      if (response.body.kind === 'single') {
        expect(response.body.singleResult.data?.createPost.title).toBe('Test Post');
      }
    });
  });
});

十、总结

10.1 GraphQL 核心知识点

GraphQL

基础

Schema 定义

Query 查询

Mutation 变更

Subscription 订阅

进阶

Resolver 函数

Context 上下文

DataLoader

中间件

工具

Apollo Server

Prisma

Apollo Client

GraphQL Yoga

性能

查询复杂度

响应缓存

Persisted Queries

N+1 解决

10.2 GraphQL vs REST 对比

维度GraphQLREST
数据获取单次请求,精确字段多次请求或过量数据
类型系统强类型 Schema无统一类型
版本控制通过字段演进URL 版本 /v1/
文档自文档化需 Swagger
缓存手动管理HTTP 缓存
实时SubscriptionWebSocket
学习曲线较陡平缓
适用场景多端 API、灵活查询简单 CRUD

10.3 最佳实践

实践说明
Schema First先设计 Schema,再实现
Naming Convention统一命名风格
Pagination使用 Connection 模式
Error Handling统一错误格式
AuthenticationJWT + 中间件
CachingDataLoader + Redis
Rate Limiting查询复杂度限制

10.4 学习路径

阶段内容资源
入门Schema、Query、MutationApollo 文档
进阶Resolver、Context、DataLoaderGraphQL 规范
实战Apollo Server + PrismaGitHub 示例
生产性能优化、安全Apollo 最佳实践

10.5 推荐资源

类型资源说明
官方文档graphql.orgGraphQL 规范
Apolloapollographql.comGraphQL 平台
Prismaprisma.io数据库 ORM
Yogathe-guild.dev/graphql/yoga轻量级服务器
GraphQL Code Generatorthe-guild.dev/graphql/codegen代码生成

本文基于 Apollo Server 4 + Prisma + React Apollo Client 编写。如有问题欢迎评论区讨论!

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐