mcpField
G
graphql-expert

graphql-expert

github.com/travisjneuman开发107129 次安装1 天前更新
代码仓库

关于 graphql-expert

graphql-expert 是面向 GraphQL API 设计与实现的技能指南,适用于构建 API 的开发者。内容涵盖模式、解析器、客户端与性能、安全等实践。

主要功能

  1. 01GraphQL 模式与类型设计
  2. 02查询、分页与变更设计
  3. 03解析器实现与上下文
  4. 04性能优化与查询限制
  5. 05认证、授权与错误处理
  6. 06订阅和客户端集成

适用场景

  1. 01规划 GraphQL API 模式
  2. 02实现分页和数据变更
  3. 03排查 N+1 查询问题
  4. 04为字段添加访问控制

安装

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

$npx skills add https://github.com/travisjneuman/.claude --skill graphql-expert

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

详细介绍

GraphQL 专家

设计和实现 GraphQL API 的综合指南。

GraphQL 基础知识

什么是 GraphQL?
GraphQL is a query language for APIs that:
✓ Lets clients request exactly what they need
✓ Gets multiple resources in one request
✓ Uses a type system to describe data
✓ Provides introspection (self-documenting)

GraphQL vs REST:
┌─────────────────────────────────────────┐
│ REST: Multiple endpoints, fixed shapes  │
│ GET /users/1                            │
│ GET /users/1/posts                      │
│ GET /users/1/followers                  │
├─────────────────────────────────────────┤
│ GraphQL: Single endpoint, flexible      │
│ POST /graphql                           │
│ query { user(id: 1) {                   │
│   name                                  │
│   posts { title }                       │
│   followers { name }                    │
│ }}                                      │
└─────────────────────────────────────────┘

Schema 设计

类型系统
# Scalar Types (built-in)
String, Int, Float, Boolean, ID

# Custom Scalar
scalar DateTime
scalar JSON

# Object Type
type User {
  id: ID!
  email: String!
  name: String
  createdAt: DateTime!
  posts: [Post!]!
}

# Enum
enum Role {
  ADMIN
  USER
  GUEST
}

# Interface
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  # ... other fields
}

# Union
union SearchResult = User | Post | Comment

# Input Type (for mutations)
input CreateUserInput {
  email: String!
  name: String!
  role: Role = USER
}
可空性
# Field modifiers:
String      # Nullable string
String!     # Non-null string
[String]    # Nullable list of nullable strings
[String!]   # Nullable list of non-null strings
[String]!   # Non-null list of nullable strings
[String!]!  # Non-null list of non-null strings

# Best practice:
# - Make fields nullable by default
# - Use ! only when guaranteed non-null
# - Lists should usually be non-null: [Item!]!
Schema 结构
# Root Types
type Query {
  # Read operations
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
  me: User
}

type Mutation {
  # Write operations
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}

type Subscription {
  # Real-time updates
  userCreated: User!
  messageReceived(roomId: ID!): Message!
}

查询设计

基本查询
# Simple query
query GetUser {
  user(id: "1") {
    name
    email
  }
}

# With variables
query GetUser($id: ID!) {
  user(id: $id) {
    name
    email
  }
}

# Multiple queries
query Dashboard {
  me {
    name
    notifications {
      count
    }
  }
  recentPosts(limit: 5) {
    title
    createdAt
  }
}
分页
# Offset-based (simple, but has issues)
type Query {
  users(limit: Int!, offset: Int!): [User!]!
}

# Cursor-based (recommended)
type Query {
  users(first: Int, after: String): UserConnection!
}

type UserConnection {
  edges: [UserEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

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

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

# Usage
query {
  users(first: 10, after: "cursor123") {
    edges {
      cursor
      node {
        name
        email
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
筛选与排序
input UserFilter {
  name: StringFilter
  email: StringFilter
  role: Role
  createdAt: DateFilter
}

input StringFilter {
  equals: String
  contains: String
  startsWith: String
}

input DateFilter {
  before: DateTime
  after: DateTime
}

enum UserSortField {
  NAME
  EMAIL
  CREATED_AT
}

input UserSort {
  field: UserSortField!
  direction: SortDirection!
}

enum SortDirection {
  ASC
  DESC
}

type Query {
  users(
    filter: UserFilter
    sort: UserSort
    first: Int
    after: String
  ): UserConnection!
}

变更

变更设计
# Input types for mutations
input CreatePostInput {
  title: String!
  content: String!
  published: Boolean = false
  categoryIds: [ID!]
}

input UpdatePostInput {
  title: String
  content: String
  published: Boolean
}

# Mutation payloads (recommended)
type CreatePostPayload {
  post: Post
  errors: [Error!]!
}

type Error {
  field: String
  message: String!
}

type Mutation {
  createPost(input: CreatePostInput!): CreatePostPayload!
  updatePost(id: ID!, input: UpdatePostInput!): UpdatePostPayload!
  deletePost(id: ID!): DeletePostPayload!
}

# Usage
mutation CreatePost($input: CreatePostInput!) {
  createPost(input: $input) {
    post {
      id
      title
    }
    errors {
      field
      message
    }
  }
}
批量变更
# For multiple operations
type Mutation {
  bulkDeletePosts(ids: [ID!]!): BulkDeletePayload!
  bulkUpdatePosts(updates: [PostUpdate!]!): BulkUpdatePayload!
}

input PostUpdate {
  id: ID!
  input: UpdatePostInput!
}

解析器

基本解析器
// TypeScript resolver implementation
const resolvers = {
  Query: {
    user: async (_, { id }, context) => {
      return context.dataSources.users.findById(id);
    },

    users: async (_, { filter, sort, first, after }, context) => {
      return context.dataSources.users.findMany({
        filter,
        sort,
        first,
        after,
      });
    },
  },

  Mutation: {
    createUser: async (_, { input }, context) => {
      // Validate
      const errors = validateCreateUser(input);
      if (errors.length) {
        return { user: null, errors };
      }

      // Create
      const user = await context.dataSources.users.create(input);
      return { user, errors: [] };
    },
  },

  // Field resolvers
  User: {
    posts: async (user, _, context) => {
      return context.dataSources.posts.findByUserId(user.id);
    },

    fullName: (user) => {
      return `${user.firstName} ${user.lastName}`;
    },
  },
};
解析器上下文
// Context setup
interface Context {
  user: User | null;
  dataSources: {
    users: UserDataSource;
    posts: PostDataSource;
  };
  loaders: {
    userLoader: DataLoader<string, User>;
    postLoader: DataLoader<string, Post>;
  };
}

// In server setup
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req }) => ({
    user: await getUserFromToken(req.headers.authorization),
    dataSources: {
      users: new UserDataSource(db),
      posts: new PostDataSource(db),
    },
    loaders: createLoaders(),
  }),
});

性能优化

DataLoader(N+1 问题解决方案)
import DataLoader from "dataloader";

// Create loader
const userLoader = new DataLoader<string, User>(async (ids) => {
  const users = await db.users.findMany({
    where: { id: { in: ids } },
  });

  // Return in same order as input ids
  const userMap = new Map(users.map((u) => [u.id, u]));
  return ids.map((id) => userMap.get(id) || null);
});

// Use in resolver
const resolvers = {
  Post: {
    author: (post, _, context) => {
      return context.loaders.userLoader.load(post.authorId);
    },
  },
};
查询复杂度
import { createComplexityLimitRule } from "graphql-validation-complexity";

// Limit query complexity
const complexityLimitRule = createComplexityLimitRule(1000, {
  scalarCost: 1,
  objectCost: 10,
  listFactor: 10,
});

// Or field-level costs
const typeDefs = gql`
  type Query {
    users: [User!]! @complexity(value: 10, multipliers: ["first"])
    user(id: ID!): User @complexity(value: 1)
  }
`;
查询深度限制
import depthLimit from "graphql-depth-limit";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(10)],
});
持久化查询
// Client sends hash instead of full query
// Reduces bandwidth, enables whitelisting

// Apollo Client setup
import { createPersistedQueryLink } from "@apollo/client/link/persisted-queries";

const link = createPersistedQueryLink({ sha256 }).concat(httpLink);

// Server validates against known queries
const server = new ApolloServer({
  typeDefs,
  resolvers,
  persistedQueries: {
    cache: new RedisCache(),
  },
});

身份验证与授权

基于上下文的身份验证
// Add user to context
const context = async ({ req }) => {
  const token = req.headers.authorization?.replace("Bearer ", "");
  const user = token ? await verifyToken(token) : null;
  return { user };
};

// Check in resolvers
const resolvers = {
  Query: {
    me: (_, __, context) => {
      if (!context.user) {
        throw new AuthenticationError("Not authenticated");
      }
      return context.user;
    },
  },
};
基于指令的身份验证
directive @auth(requires: Role = USER) on FIELD_DEFINITION

type Query {
  publicPosts: [Post!]!
  me: User @auth
  adminDashboard: Dashboard @auth(requires: ADMIN)
}
// Directive implementation
class AuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    const requiredRole = this.args.requires;

    field.resolve = async function (...args) {
      const context = args[2];

      if (!context.user) {
        throw new AuthenticationError("Not authenticated");
      }

      if (requiredRole && context.user.role !== requiredRole) {
        throw new ForbiddenError("Not authorized");
      }

      return resolve.apply(this, args);
    };
  }
}

错误处理

错误类型
import {
  ApolloError,
  AuthenticationError,
  ForbiddenError,
  UserInputError,
} from "apollo-server";

// Validation errors
throw new UserInputError("Invalid email format", {
  field: "email",
});

// Auth errors
throw new AuthenticationError("Must be logged in");
throw new ForbiddenError("Not authorized to view this resource");

// Custom errors
class NotFoundError extends ApolloError {
  constructor(resource: string) {
    super(`${resource} not found`, "NOT_FOUND");
  }
}
错误格式化
const server = new ApolloServer({
  formatError: (error) => {
    // Log internal errors
    if (error.extensions?.code === "INTERNAL_SERVER_ERROR") {
      console.error(error);
      return new Error("Internal server error");
    }

    // Mask sensitive info
    if (error.message.includes("password")) {
      return new Error("An error occurred");
    }

    return error;
  },
});

订阅

设置
type Subscription {
  messageCreated(roomId: ID!): Message!
  userStatusChanged(userId: ID!): UserStatus!
}
import { PubSub } from "graphql-subscriptions";

const pubsub = new PubSub();

const resolvers = {
  Mutation: {
    sendMessage: async (_, { input }, context) => {
      const message = await createMessage(input);

      pubsub.publish(`MESSAGE_CREATED_${input.roomId}`, {
        messageCreated: message,
      });

      return message;
    },
  },

  Subscription: {
    messageCreated: {
      subscribe: (_, { roomId }) => {
        return pubsub.asyncIterator(`MESSAGE_CREATED_${roomId}`);
      },
    },
  },
};
带筛选的订阅
import { withFilter } from "graphql-subscriptions";

const resolvers = {
  Subscription: {
    messageCreated: {
      subscribe: withFilter(
        () => pubsub.asyncIterator("MESSAGE_CREATED"),
        (payload, variables, context) => {
          // Only send to users in the room
          return (
            payload.messageCreated.roomId === variables.roomId &&
            context.user.rooms.includes(variables.roomId)
          );
        },
      ),
    },
  },
};

客户端集成

Apollo Client 设置
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const httpLink = createHttpLink({
  uri: "/graphql",
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("token");
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});
React Hooks
import { useQuery, useMutation, gql } from '@apollo/client';

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;

function UserProfile({ userId }) {
  const { loading, error, data } = useQuery(GET_USER, {
    variables: { id: userId },
  });

  if (loading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return <div>{data.user.name}</div>;
}

// Mutation
const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      post { id title }
      errors { field message }
    }
  }
`;

function CreatePostForm() {
  const [createPost, { loading }] = useMutation(CREATE_POST, {
    update(cache, { data }) {
      // Update cache after mutation
    },
  });

  const handleSubmit = async (input) => {
    const { data } = await createPost({ variables: { input } });
    if (data.createPost.errors.length) {
      // Handle errors
    }
  };
}

最佳实践

应该:
  • 从客户端视角设计 schema
  • 在变更中使用输入类型
  • 让变更返回包含错误的负载
  • 实现 DataLoader 以防止 N+1 问题
  • 使用基于游标的分页
  • 添加查询复杂度限制
  • 谨慎管理 schema 版本
不应该:
  • 直接暴露数据库 schema
  • 不必要地创建深度嵌套的类型
  • 忽略授权
  • 允许无界查询
  • 跳过错误处理
  • 忽视缓存策略
  • 在查询中变更数据

Schema 检查清单

  • 类型命名清晰(单数形式,PascalCase)
  • 可空性模式保持一致
  • 所有变更都使用输入类型
  • 负载类型包含错误处理
  • 所有列表都支持分页
  • 已考虑身份验证/授权
  • 已实施性能优化

评论

支持 Markdown