mcpField
G
graphql-api-development

graphql-api-development

github.com/manutej开发62447 次安装40 周前更新
代码仓库

关于 graphql-api-development

graphql-api-development 是面向使用 graphql-js 构建 GraphQL API 的开发者的学习技能,涵盖模式设计、解析器、实时订阅、安全、性能、测试与部署。

主要功能

  1. 01模式与类型系统设计
  2. 02查询、变更与解析器
  3. 03实时订阅
  4. 04身份验证与授权模式
  5. 05缓存与查询优化
  6. 06API 测试与部署实践

适用场景

  1. 01为数据需求各异的客户端构建 API
  2. 02提供嵌套数据关系
  3. 03通过订阅添加实时更新
  4. 04限制开销高或嵌套过深的查询

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/manutej/luxor-claude-marketplace --skill graphql-api-development

安装后在 Claude Code 中输入/graphql-api-development确认已加载。

附带文件EXAMPLES.mdREADME.md

详细介绍

GraphQL API 开发

一项全面的技能,涵盖如何使用 graphql-js 构建可用于生产环境的 GraphQL API。掌握模式设计、类型系统、解析器、查询、变更、订阅、身份验证、授权、缓存、测试和部署策略。

何时使用此技能

在以下情况下使用此技能:

  • 构建需要为 Web 或移动客户端灵活获取数据的新 API
  • 用更高效的数据访问模式替代或扩展 REST API
  • 为具有复杂嵌套数据关系的应用开发 API
  • 创建服务于多种客户端(Web、移动端、桌面端)且数据需求各异的 API
  • 构建需要订阅和实时更新的实时应用
  • 设计客户端需要精确指定所需数据的 API
  • 使用 Node.js 和 Express 开发 GraphQL 服务
  • 实现具有严格模式验证的类型安全 API
  • 创建内置自省功能的自描述 API
  • 构建需要组合成统一 API 的微服务

GraphQL 优于 REST 的场景

GraphQL 的优势
  1. 精确获取数据:客户端只请求所需数据,不会过度或不足获取
  2. 单次请求:通过一次往返即可获取多个资源,而非调用多个 REST 端点
  3. 强类型:模式定义了确切的类型,可实现验证并提供工具支持
  4. 自省:可查询模式的自描述 API
  5. 无需版本控制:添加新字段时不会破坏现有查询
  6. 实时更新:内置订阅支持,可获取实时数据
  7. 嵌套资源:自然处理复杂关系,无需发出 N+1 个查询
  8. 客户端驱动:客户端控制数据结构,减少后端变更
适合继续使用 REST 的场景
  • 使用标准资源执行简单的 CRUD 操作
  • 文件上传/下载(GraphQL 需要处理 multipart)
  • HTTP 缓存至关重要(GraphQL 通常使用 POST)
  • 团队不熟悉 GraphQL(存在学习曲线)
  • 现有 REST 基础设施运行良好

核心概念

GraphQL 类型系统

GraphQL 的类型系统是其基础。每个 GraphQL API 都定义了:

  1. 标量类型:基本数据类型(String、Int、Float、Boolean、ID)
  2. 对象类型:包含字段的复杂类型
  3. 查询类型:读取操作的入口
  4. 变更类型:写入操作的入口
  5. 订阅类型:实时更新的入口
  6. 输入类型:用于变更的复杂输入
  7. 枚举:固定的值集合
  8. 接口:对象可实现的抽象类型
  9. 联合:可属于多种类型之一的类型
  10. 非空类型:不能为 null 的类型
  11. 列表类型:类型数组
模式定义

定义 GraphQL 模式有两种方式:

1. 模式定义语言(SDL) - 声明式、易读:

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

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

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

2. 编程式 API - 类型安全、以编程方式定义:

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    name: { type: new GraphQLNonNull(GraphQLString) },
    email: { type: new GraphQLNonNull(GraphQLString) },
    posts: { type: new GraphQLList(new GraphQLNonNull(PostType)) }
  }
});
解析器

解析器是为模式字段返回数据的函数。每个字段都可以有一个解析器:

const resolvers = {
  Query: {
    user: (parent, args, context, info) => {
      return context.db.findUserById(args.id);
    }
  },
  User: {
    posts: (user, args, context) => {
      return context.db.findPostsByAuthorId(user.id);
    }
  }
};

解析器函数签名:

  • parent:父级解析器的结果
  • args:传递给字段的参数
  • context:共享上下文(数据库、身份验证等)
  • info:字段专属元数据
查询

查询用于从 API 获取数据:

query GetUser {
  user(id: "123") {
    id
    name
    email
    posts {
      title
      content
    }
  }
}
变更

变更用于修改数据:

mutation CreatePost {
  createPost(input: {
    title: "GraphQL is awesome"
    content: "Here's why..."
    authorId: "123"
  }) {
    id
    title
    author {
      name
    }
  }
}
订阅

订阅用于启用实时更新:

subscription OnPostCreated {
  postCreated {
    id
    title
    author {
      name
    }
  }
}

模式设计模式

模式 1:变更使用输入类型

复杂的变更参数始终使用输入类型:

input CreateUserInput {
  name: String!
  email: String!
  age: Int
  bio: String
}

type Mutation {
  createUser(input: CreateUserInput!): User!
}

原因:更易于扩展,组织更清晰,还可在多个变更中重复使用。

模式 2:使用接口共享字段

多个类型共享字段时,使用接口:

interface Node {
  id: ID!
  createdAt: String!
  updatedAt: String!
}

type User implements Node {
  id: ID!
  createdAt: String!
  updatedAt: String!
  name: String!
  email: String!
}

type Post implements Node {
  id: ID!
  createdAt: String!
  updatedAt: String!
  title: String!
  content: String
}
模式 3:使用联合实现多态返回值

字段可能返回不同类型时,使用联合:

union SearchResult = User | Post | Comment

type Query {
  search(query: String!): [SearchResult!]!
}
模式 4:分页模式

基于偏移量的分页:

type Query {
  posts(offset: Int, limit: Int): PostConnection!
}

type PostConnection {
  items: [Post!]!
  total: Int!
  hasMore: Boolean!
}

基于游标的分页(Relay 风格):

type Query {
  posts(first: Int, after: String): PostConnection!
}

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

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

type PageInfo {
  hasNextPage: Boolean!
  endCursor: String
}
模式 5:错误处理

字段级错误:

type MutationPayload {
  success: Boolean!
  message: String
  user: User
  errors: [Error!]
}

type Error {
  field: String!
  message: String!
}

基于联合类型的错误处理:

union CreateUserResult = User | ValidationError | DatabaseError

type ValidationError {
  field: String!
  message: String!
}
模式 6:使用指令进行版本管理

弃用字段,而不是进行版本管理:

type User {
  name: String! @deprecated(reason: "Use firstName and lastName")
  firstName: String!
  lastName: String!
}

查询优化与性能

N+1 问题

问题:获取嵌套数据会导致执行多个数据库查询:

// BAD: N+1 queries
const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    posts: {
      type: new GraphQLList(PostType),
      resolve: (user) => {
        // This runs once PER user!
        return db.getPostsByUserId(user.id);
      }
    }
  }
});

// Query for 100 users = 1 query for users + 100 queries for posts = 101 queries
DataLoader 解决方案

DataLoader 会批量处理请求并缓存结果:

import DataLoader from 'dataloader';

// Create DataLoader
const postLoader = new DataLoader(async (userIds) => {
  // Single query for all user IDs
  const posts = await db.getPostsByUserIds(userIds);

  // Group posts by userId
  const postsByUserId = {};
  posts.forEach(post => {
    if (!postsByUserId[post.authorId]) {
      postsByUserId[post.authorId] = [];
    }
    postsByUserId[post.authorId].push(post);
  });

  // Return in same order as userIds
  return userIds.map(id => postsByUserId[id] || []);
});

// Use in resolver
const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    posts: {
      type: new GraphQLList(PostType),
      resolve: (user, args, context) => {
        return context.loaders.postLoader.load(user.id);
      }
    }
  }
});

// Add to context
const context = {
  loaders: {
    postLoader: new DataLoader(batchLoadPosts)
  }
};
查询复杂度分析

限制开销大的查询:

import { getComplexity, simpleEstimator } from 'graphql-query-complexity';

const complexity = getComplexity({
  schema,
  query,
  estimators: [
    simpleEstimator({ defaultComplexity: 1 })
  ]
});

if (complexity > 1000) {
  throw new Error('Query too complex');
}
深度限制

防止查询嵌套过深:

import depthLimit from 'graphql-depth-limit';

const server = new ApolloServer({
  schema,
  validationRules: [depthLimit(5)]
});

变更与输入验证

变更设计模式
input CreatePostInput {
  title: String!
  content: String!
  authorId: ID!
  tags: [String!]
}

type CreatePostPayload {
  post: Post
  errors: [UserError!]
  success: Boolean!
}

type UserError {
  message: String!
  field: String
}

type Mutation {
  createPost(input: CreatePostInput!): CreatePostPayload!
}
输入验证
const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    createPost: {
      type: CreatePostPayload,
      args: {
        input: { type: new GraphQLNonNull(CreatePostInput) }
      },
      resolve: async (_, { input }, context) => {
        // Validate input
        const errors = [];

        if (input.title.length < 3) {
          errors.push({
            field: 'title',
            message: 'Title must be at least 3 characters'
          });
        }

        if (input.content.length < 10) {
          errors.push({
            field: 'content',
            message: 'Content must be at least 10 characters'
          });
        }

        if (errors.length > 0) {
          return { errors, success: false, post: null };
        }

        // Create post
        const post = await context.db.createPost(input);
        return { post, errors: [], success: true };
      }
    }
  }
});

订阅与实时更新

设置订阅
import { GraphQLObjectType, GraphQLString } from 'graphql';
import { PubSub } from 'graphql-subscriptions';

const pubsub = new PubSub();

const Subscription = new GraphQLObjectType({
  name: 'Subscription',
  fields: {
    postCreated: {
      type: PostType,
      subscribe: () => pubsub.asyncIterator(['POST_CREATED'])
    },
    messageReceived: {
      type: MessageType,
      args: {
        channelId: { type: new GraphQLNonNull(GraphQLID) }
      },
      subscribe: (_, { channelId }) => {
        return pubsub.asyncIterator([`MESSAGE_${channelId}`]);
      }
    }
  }
});
发布事件
const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    createPost: {
      type: PostType,
      args: {
        input: { type: new GraphQLNonNull(CreatePostInput) }
      },
      resolve: async (_, { input }, context) => {
        const post = await context.db.createPost(input);

        // Publish to subscribers
        pubsub.publish('POST_CREATED', { postCreated: post });

        return post;
      }
    }
  }
});
WebSocket 服务端设置
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { execute, subscribe } from 'graphql';
import express from 'express';

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

// WebSocket server for subscriptions
const wsServer = new WebSocketServer({
  server: httpServer,
  path: '/graphql'
});

useServer(
  {
    schema,
    execute,
    subscribe,
    context: (ctx) => {
      // Access connection params, headers
      return {
        userId: ctx.connectionParams?.userId,
        db: database
      };
    }
  },
  wsServer
);

httpServer.listen(4000);

身份验证与授权

基于上下文的身份验证
import jwt from 'jsonwebtoken';

// Middleware to extract user
const authMiddleware = async (req) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    return { user: null };
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await db.findUserById(decoded.userId);
    return { user };
  } catch (error) {
    return { user: null };
  }
};

// Add to GraphQL context
app.all('/graphql', async (req, res) => {
  const auth = await authMiddleware(req);

  createHandler({
    schema,
    context: {
      user: auth.user,
      db: database
    }
  })(req, res);
});
解析器级授权
const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    me: {
      type: UserType,
      resolve: (_, __, context) => {
        if (!context.user) {
          throw new Error('Authentication required');
        }
        return context.user;
      }
    },
    adminData: {
      type: GraphQLString,
      resolve: (_, __, context) => {
        if (!context.user) {
          throw new Error('Authentication required');
        }

        if (context.user.role !== 'admin') {
          throw new Error('Admin access required');
        }

        return 'Secret admin data';
      }
    }
  }
});
字段级授权
const PostType = new GraphQLObjectType({
  name: 'Post',
  fields: {
    title: { type: GraphQLString },
    content: { type: GraphQLString },
    draft: {
      type: GraphQLBoolean,
      resolve: (post, args, context) => {
        // Only author can see draft status
        if (post.authorId !== context.user?.id) {
          return null;
        }
        return post.draft;
      }
    }
  }
});
基于指令的授权
directive @auth(requires: Role = USER) on FIELD_DEFINITION

enum Role {
  USER
  ADMIN
  MODERATOR
}

type Query {
  publicData: String
  userData: String @auth(requires: USER)
  adminData: String @auth(requires: ADMIN)
}
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';

function authDirective(schema, directiveName) {
  return mapSchema(schema, {
    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
      const authDirective = getDirective(schema, fieldConfig, directiveName)?.[0];

      if (authDirective) {
        const { requires } = authDirective;
        const { resolve = defaultFieldResolver } = fieldConfig;

        fieldConfig.resolve = async (source, args, context, info) => {
          if (!context.user) {
            throw new Error('Authentication required');
          }

          if (context.user.role !== requires) {
            throw new Error(`${requires} role required`);
          }

          return resolve(source, args, context, info);
        };
      }

      return fieldConfig;
    }
  });
}

缓存策略

内存缓存
import { LRUCache } from 'lru-cache';

const cache = new LRUCache({
  max: 500,
  ttl: 1000 * 60 * 5 // 5 minutes
});

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    product: {
      type: ProductType,
      args: { id: { type: new GraphQLNonNull(GraphQLID) } },
      resolve: async (_, { id }, context) => {
        const cacheKey = `product:${id}`;
        const cached = cache.get(cacheKey);

        if (cached) {
          return cached;
        }

        const product = await context.db.findProductById(id);
        cache.set(cacheKey, product);
        return product;
      }
    }
  }
});
Redis 缓存
import Redis from 'ioredis';

const redis = new Redis({
  host: process.env.REDIS_HOST,
  port: process.env.REDIS_PORT
});

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: UserType,
      args: { id: { type: new GraphQLNonNull(GraphQLID) } },
      resolve: async (_, { id }, context) => {
        const cacheKey = `user:${id}`;

        // Check cache
        const cached = await redis.get(cacheKey);
        if (cached) {
          return JSON.parse(cached);
        }

        // Fetch from database
        const user = await context.db.findUserById(id);

        // Cache for 10 minutes
        await redis.setex(cacheKey, 600, JSON.stringify(user));

        return user;
      }
    }
  }
});
缓存失效
const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    updateUser: {
      type: UserType,
      args: {
        id: { type: new GraphQLNonNull(GraphQLID) },
        input: { type: new GraphQLNonNull(UpdateUserInput) }
      },
      resolve: async (_, { id, input }, context) => {
        const user = await context.db.updateUser(id, input);

        // Invalidate cache
        const cacheKey = `user:${id}`;
        await redis.del(cacheKey);

        // Also invalidate list caches
        await redis.del('users:all');

        return user;
      }
    }
  }
});

错误处理

自定义错误类
class AuthenticationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AuthenticationError';
    this.extensions = { code: 'UNAUTHENTICATED' };
  }
}

class ForbiddenError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ForbiddenError';
    this.extensions = { code: 'FORBIDDEN' };
  }
}

class ValidationError extends Error {
  constructor(message, fields) {
    super(message);
    this.name = 'ValidationError';
    this.extensions = {
      code: 'BAD_USER_INPUT',
      fields
    };
  }
}
错误格式化
import { formatError } from 'graphql';

const customFormatError = (error) => {
  // Log error for monitoring
  console.error('GraphQL Error:', {
    message: error.message,
    locations: error.locations,
    path: error.path,
    extensions: error.extensions
  });

  // Don't expose internal errors to clients
  if (error.message.startsWith('Database')) {
    return {
      message: 'Internal server error',
      extensions: { code: 'INTERNAL_SERVER_ERROR' }
    };
  }

  return formatError(error);
};

const server = new ApolloServer({
  schema,
  formatError: customFormatError
});
优雅的错误响应
const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: UserType,
      args: { id: { type: new GraphQLNonNull(GraphQLID) } },
      resolve: async (_, { id }, context) => {
        try {
          const user = await context.db.findUserById(id);

          if (!user) {
            throw new Error(`User with ID ${id} not found`);
          }

          return user;
        } catch (error) {
          // Log error
          console.error('Error fetching user:', error);

          // Re-throw with user-friendly message
          if (error.code === 'ECONNREFUSED') {
            throw new Error('Unable to connect to database');
          }

          throw error;
        }
      }
    }
  }
});

测试 GraphQL API

解析器单元测试
import { describe, it, expect, jest } from '@jest/globals';

describe('User resolver', () => {
  it('returns user by ID', async () => {
    const mockDb = {
      findUserById: jest.fn().mockResolvedValue({
        id: '1',
        name: 'Alice',
        email: '[email protected]'
      })
    };

    const context = { db: mockDb };
    const result = await userResolver.resolve(null, { id: '1' }, context);

    expect(mockDb.findUserById).toHaveBeenCalledWith('1');
    expect(result).toEqual({
      id: '1',
      name: 'Alice',
      email: '[email protected]'
    });
  });

  it('throws error for non-existent user', async () => {
    const mockDb = {
      findUserById: jest.fn().mockResolvedValue(null)
    };

    const context = { db: mockDb };

    await expect(
      userResolver.resolve(null, { id: '999' }, context)
    ).rejects.toThrow('User with ID 999 not found');
  });
});
集成测试
import { graphql } from 'graphql';
import { schema } from './schema';

describe('GraphQL Schema', () => {
  it('executes user query', async () => {
    const query = `
      query {
        user(id: "1") {
          id
          name
          email
        }
      }
    `;

    const result = await graphql({
      schema,
      source: query,
      contextValue: {
        db: mockDatabase,
        user: null
      }
    });

    expect(result.errors).toBeUndefined();
    expect(result.data?.user).toEqual({
      id: '1',
      name: 'Alice',
      email: '[email protected]'
    });
  });

  it('handles authentication errors', async () => {
    const query = `
      query {
        me {
          id
          name
        }
      }
    `;

    const result = await graphql({
      schema,
      source: query,
      contextValue: {
        db: mockDatabase,
        user: null
      }
    });

    expect(result.errors).toBeDefined();
    expect(result.errors[0].message).toBe('Authentication required');
  });
});
使用 Apollo Server 进行测试
import { ApolloServer } from '@apollo/server';

const testServer = new ApolloServer({
  schema,
});

describe('User queries', () => {
  it('fetches user successfully', async () => {
    const response = await testServer.executeOperation({
      query: `
        query GetUser($id: ID!) {
          user(id: $id) {
            id
            name
          }
        }
      `,
      variables: { id: '1' }
    });

    expect(response.body.singleResult.errors).toBeUndefined();
    expect(response.body.singleResult.data?.user).toMatchObject({
      id: '1',
      name: expect.any(String)
    });
  });
});

生产环境最佳实践

Schema 组织
src/
├── schema/
│   ├── index.js          # Combine all types
│   ├── types/
│   │   ├── user.js       # User type and resolvers
│   │   ├── post.js       # Post type and resolvers
│   │   └── comment.js    # Comment type and resolvers
│   ├── queries/
│   │   ├── user.js       # User queries
│   │   └── post.js       # Post queries
│   ├── mutations/
│   │   ├── user.js       # User mutations
│   │   └── post.js       # Post mutations
│   └── subscriptions/
│       └── post.js       # Post subscriptions
├── directives/
│   └── auth.js           # Authorization directive
├── utils/
│   ├── loaders.js        # DataLoader instances
│   └── context.js        # Context builder
└── server.js             # Server setup
监控与日志记录
import { ApolloServerPluginLandingPageGraphQLPlayground } from '@apollo/server-plugin-landing-page-graphql-playground';

const server = new ApolloServer({
  schema,
  plugins: [
    // Request logging
    {
      async requestDidStart(requestContext) {
        console.log('Request started:', requestContext.request.query);

        return {
          async didEncounterErrors(ctx) {
            console.error('Errors:', ctx.errors);
          },
          async willSendResponse(ctx) {
            console.log('Response sent');
          }
        };
      }
    },

    // Performance monitoring
    {
      async requestDidStart() {
        const start = Date.now();

        return {
          async willSendResponse() {
            const duration = Date.now() - start;
            console.log(`Request duration: ${duration}ms`);
          }
        };
      }
    }
  ]
});
速率限制
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per window
  message: 'Too many requests, please try again later'
});

app.use('/graphql', limiter);
查询白名单
const allowedQueries = new Set([
  'query GetUser { user(id: $id) { id name email } }',
  'mutation CreatePost { createPost(input: $input) { id title } }'
]);

const validateQuery = (query) => {
  const normalized = query.replace(/\s+/g, ' ').trim();
  if (!allowedQueries.has(normalized)) {
    throw new Error('Query not whitelisted');
  }
};
安全标头
import helmet from 'helmet';

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
    }
  },
  crossOriginEmbedderPolicy: false
}));

高级模式

Federation(微服务)
import { buildSubgraphSchema } from '@apollo/subgraph';

// Users service
const userSchema = buildSubgraphSchema({
  typeDefs: `
    type User @key(fields: "id") {
      id: ID!
      name: String!
      email: String!
    }
  `,
  resolvers: {
    User: {
      __resolveReference(user) {
        return findUserById(user.id);
      }
    }
  }
});

// Posts service
const postSchema = buildSubgraphSchema({
  typeDefs: `
    type Post {
      id: ID!
      title: String!
      author: User!
    }

    extend type User @key(fields: "id") {
      id: ID! @external
      posts: [Post!]!
    }
  `,
  resolvers: {
    Post: {
      author(post) {
        return { __typename: 'User', id: post.authorId };
      }
    },
    User: {
      posts(user) {
        return findPostsByAuthorId(user.id);
      }
    }
  }
});
自定义标量
import { GraphQLScalarType, Kind } from 'graphql';

const DateTimeScalar = new GraphQLScalarType({
  name: 'DateTime',
  description: 'ISO-8601 DateTime string',

  serialize(value) {
    // Send to client
    return value instanceof Date ? value.toISOString() : null;
  },

  parseValue(value) {
    // From variables
    return new Date(value);
  },

  parseLiteral(ast) {
    // From query string
    if (ast.kind === Kind.STRING) {
      return new Date(ast.value);
    }
    return null;
  }
});

// Use in schema
const schema = new GraphQLSchema({
  types: [DateTimeScalar],
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      now: {
        type: DateTimeScalar,
        resolve: () => new Date()
      }
    }
  })
});
批量操作
const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    batchCreateUsers: {
      type: new GraphQLList(UserType),
      args: {
        inputs: {
          type: new GraphQLNonNull(
            new GraphQLList(new GraphQLNonNull(CreateUserInput))
          )
        }
      },
      resolve: async (_, { inputs }, context) => {
        const users = await Promise.all(
          inputs.map(input => context.db.createUser(input))
        );
        return users;
      }
    }
  }
});

常见模式总结

  1. 使用输入类型:为所有包含多个参数的变更使用输入类型
  2. 实现 DataLoader:解决嵌套数据查询中的 N+1 问题
  3. 添加分页:用于可能无限增长的列表字段
  4. 妥善处理错误:返回对用户友好的错误消息
  5. 验证输入:在执行数据库操作之前,于解析器级别进行验证
  6. 使用上下文共享状态:数据库、身份验证、加载器
  7. 实现授权:在解析器级别或指令级别实现
  8. 积极缓存:使用 Redis 或内存缓存频繁访问的数据
  9. 监控性能:跟踪查询复杂度和执行时间
  10. 使用 @deprecated 管理版本:绝不破坏现有查询
  11. 全面测试:对解析器进行单元测试,对查询进行集成测试
  12. 记录 Schema 文档:在 SDL 中使用描述
  13. 谨慎使用非空类型:仅用于真正必需的字段
  14. 组织 Schema:按领域拆分为多个模块
  15. 保障生产环境安全:速率限制、查询白名单、深度限制

资源与工具

必备库
  • graphql-js:GraphQL 核心实现
  • express:Web 服务端框架
  • graphql-http:GraphQL 的 HTTP 处理程序
  • dataloader:批量处理与缓存
  • graphql-ws:用于订阅的 WebSocket 服务端
  • graphql-scalars:常见的自定义标量
  • graphql-tools:Schema 操作工具集
开发工具
  • GraphiQL:浏览器内的 GraphQL IDE
  • GraphQL Playground:高级 GraphQL IDE
  • Apollo Studio:Schema 注册表与监控
  • GraphQL Code Generator:生成 TypeScript 类型
  • eslint-plugin-graphql:检查 GraphQL 查询
学习资源

Skill 版本:1.0.0 最后更新:2025 年 10 月 Skill 类别:API 开发、后端、GraphQL、Web 开发 兼容环境:Node.js、Express、TypeScript、JavaScript

评论

支持 Markdown