[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-92fbc2d1-4f86-4622-915d-15c85ac42d18":3,"$fbxe_CWWzNW_k80dQ04bOHC4zj3IwaLUcFteLXJmbMgA":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"92fbc2d1-4f86-4622-915d-15c85ac42d18","graphql","GraphQL为客户端提供他们所需的确切数据——不多也不少","cat_coding_backend","mod_coding","sickn33,coding","---\nname: graphql\ndescription: GraphQL gives clients exactly the data they need - no more, no\n  less. One endpoint, typed schema, introspection. But the flexibility that\n  makes it powerful also makes it dangerous. Without proper controls, clients\n  can craft queries that bring down your server.\nrisk: safe\nsource: vibeship-spawner-skills (Apache 2.0)\ndate_added: 2026-02-27\n---\n\n# GraphQL\n\nGraphQL gives clients exactly the data they need - no more, no less. One\nendpoint, typed schema, introspection. But the flexibility that makes it\npowerful also makes it dangerous. Without proper controls, clients can\ncraft queries that bring down your server.\n\nThis skill covers schema design, resolvers, DataLoader for N+1 prevention,\nfederation for microservices, and client integration with Apollo\u002Furql.\nKey insight: GraphQL is a contract. The schema is the API documentation.\nDesign it carefully.\n\n2025 lesson: GraphQL isn't always the answer. For simple CRUD, REST is\nsimpler. For high-performance public APIs, REST with caching wins. Use\nGraphQL when you have complex data relationships and diverse client needs.\n\n## Principles\n\n- Schema-first design - the schema is the contract\n- Prevent N+1 queries with DataLoader\n- Limit query depth and complexity\n- Use fragments for reusable selections\n- Mutations should be specific, not generic update operations\n- Errors are data - use union types for expected failures\n- Nullability is meaningful - design it intentionally\n\n## Capabilities\n\n- graphql-schema-design\n- graphql-resolvers\n- graphql-federation\n- graphql-subscriptions\n- graphql-dataloader\n- graphql-codegen\n- apollo-server\n- apollo-client\n- urql\n\n## Scope\n\n- database-queries -> postgres-wizard\n- authentication -> authentication-oauth\n- rest-api-design -> backend\n- websocket-infrastructure -> backend\n\n## Tooling\n\n### Server\n\n- @apollo\u002Fserver - When: Apollo Server v4 Note: Most popular GraphQL server\n- graphql-yoga - When: Lightweight alternative Note: Good for serverless\n- mercurius - When: Fastify integration Note: Fast, uses JIT\n\n### Client\n\n- @apollo\u002Fclient - When: Full-featured client Note: Caching, state management\n- urql - When: Lightweight alternative Note: Smaller, simpler\n- graphql-request - When: Simple requests Note: Minimal, no caching\n\n### Tools\n\n- graphql-codegen - When: Type generation Note: Essential for TypeScript\n- dataloader - When: N+1 prevention Note: Batches and caches\n\n## Patterns\n\n### Schema Design\n\nType-safe schema with proper nullability\n\n**When to use**: Designing any GraphQL API\n\n# SCHEMA DESIGN:\n\n\"\"\"\nThe schema is your API contract. Design nullability\nintentionally - non-null fields must always resolve.\n\"\"\"\n\ntype Query {\n  # Non-null - will always return user or throw\n  user(id: ID!): User!\n\n  # Nullable - returns null if not found\n  userByEmail(email: String!): User\n\n  # Non-null list with non-null items\n  users(limit: Int = 10, offset: Int = 0): [User!]!\n\n  # Search with pagination\n  searchUsers(\n    query: String!\n    first: Int\n    after: String\n  ): UserConnection!\n}\n\ntype Mutation {\n  # Input types for complex mutations\n  createUser(input: CreateUserInput!): CreateUserPayload!\n  updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!\n  deleteUser(id: ID!): DeleteUserPayload!\n}\n\ntype Subscription {\n  userCreated: User!\n  messageReceived(roomId: ID!): Message!\n}\n\n# Input types\ninput CreateUserInput {\n  email: String!\n  name: String!\n  role: Role = USER\n}\n\ninput UpdateUserInput {\n  email: String\n  name: String\n  role: Role\n}\n\n# Payload types (for errors as data)\ntype CreateUserPayload {\n  user: User\n  errors: [Error!]!\n}\n\nunion UpdateUserPayload = UpdateUserSuccess | NotFoundError | ValidationError\n\ntype UpdateUserSuccess {\n  user: User!\n}\n\n# Enums\nenum Role {\n  USER\n  ADMIN\n  MODERATOR\n}\n\n# Types with relationships\ntype User {\n  id: ID!\n  email: String!\n  name: String!\n  role: Role!\n  posts(limit: Int = 10): [Post!]!\n  createdAt: DateTime!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  content: String!\n  author: User!\n  comments: [Comment!]!\n  published: Boolean!\n}\n\n# Pagination (Relay-style)\ntype UserConnection {\n  edges: [UserEdge!]!\n  pageInfo: PageInfo!\n  totalCount: Int!\n}\n\ntype UserEdge {\n  node: User!\n  cursor: String!\n}\n\ntype PageInfo {\n  hasNextPage: Boolean!\n  hasPreviousPage: Boolean!\n  startCursor: String\n  endCursor: String\n}\n\n### DataLoader for N+1 Prevention\n\nBatch and cache database queries\n\n**When to use**: Resolving relationships\n\n# DATALOADER:\n\n\"\"\"\nWithout DataLoader, fetching 10 posts with authors\nmakes 11 queries (1 for posts + 10 for each author).\nDataLoader batches into 2 queries.\n\"\"\"\n\nimport DataLoader from 'dataloader';\n\n\u002F\u002F Create loaders per request\nfunction createLoaders(db) {\n  return {\n    userLoader: new DataLoader(async (ids) => {\n      \u002F\u002F Single query for all users\n      const users = await db.user.findMany({\n        where: { id: { in: ids } }\n      });\n\n      \u002F\u002F Return in same order as ids\n      const userMap = new Map(users.map(u => [u.id, u]));\n      return ids.map(id => userMap.get(id) || null);\n    }),\n\n    postsByAuthorLoader: new DataLoader(async (authorIds) => {\n      const posts = await db.post.findMany({\n        where: { authorId: { in: authorIds } }\n      });\n\n      \u002F\u002F Group by author\n      const postsByAuthor = new Map();\n      posts.forEach(post => {\n        const existing = postsByAuthor.get(post.authorId) || [];\n        postsByAuthor.set(post.authorId, [...existing, post]);\n      });\n\n      return authorIds.map(id => postsByAuthor.get(id) || []);\n    })\n  };\n}\n\n\u002F\u002F Attach to context\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n});\n\napp.use('\u002Fgraphql', expressMiddleware(server, {\n  context: async ({ req }) => ({\n    db,\n    loaders: createLoaders(db),\n    user: req.user\n  })\n}));\n\n\u002F\u002F Use in resolvers\nconst resolvers = {\n  Post: {\n    author: (post, _, { loaders }) => {\n      return loaders.userLoader.load(post.authorId);\n    }\n  },\n  User: {\n    posts: (user, _, { loaders }) => {\n      return loaders.postsByAuthorLoader.load(user.id);\n    }\n  }\n};\n\n### Apollo Client Caching\n\nNormalized cache with type policies\n\n**When to use**: Client-side data management\n\n# APOLLO CLIENT CACHING:\n\n\"\"\"\nApollo Client normalizes responses into a flat cache.\nConfigure type policies for custom cache behavior.\n\"\"\"\n\nimport { ApolloClient, InMemoryCache } from '@apollo\u002Fclient';\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        \u002F\u002F Paginated field\n        users: {\n          keyArgs: ['query'],  \u002F\u002F Cache separately per query\n          merge(existing = { edges: [] }, incoming, { args }) {\n            \u002F\u002F Append for infinite scroll\n            if (args?.after) {\n              return {\n                ...incoming,\n                edges: [...existing.edges, ...incoming.edges]\n              };\n            }\n            return incoming;\n          }\n        }\n      }\n    },\n    User: {\n      keyFields: ['id'],  \u002F\u002F How to identify users\n      fields: {\n        fullName: {\n          read(_, { readField }) {\n            \u002F\u002F Computed field\n            return `${readField('firstName')} ${readField('lastName')}`;\n          }\n        }\n      }\n    }\n  }\n});\n\nconst client = new ApolloClient({\n  uri: '\u002Fgraphql',\n  cache,\n  defaultOptions: {\n    watchQuery: {\n      fetchPolicy: 'cache-and-network'\n    }\n  }\n});\n\n\u002F\u002F Queries with hooks\nimport { useQuery, useMutation } from '@apollo\u002Fclient';\n\nconst GET_USER = gql`\n  query GetUser($id: ID!) {\n    user(id: $id) {\n      id\n      name\n      email\n    }\n  }\n`;\n\nfunction UserProfile({ userId }) {\n  const { data, loading, error } = useQuery(GET_USER, {\n    variables: { id: userId }\n  });\n\n  if (loading) return \u003CSpinner \u002F>;\n  if (error) return \u003CError message={error.message} \u002F>;\n\n  return \u003Cdiv>{data.user.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Mutations with cache updates\nconst CREATE_USER = gql`\n  mutation CreateUser($input: CreateUserInput!) {\n    createUser(input: $input) {\n      user {\n        id\n        name\n        email\n      }\n      errors {\n        field\n        message\n      }\n    }\n  }\n`;\n\nfunction CreateUserForm() {\n  const [createUser, { loading }] = useMutation(CREATE_USER, {\n    update(cache, { data: { createUser } }) {\n      \u002F\u002F Update cache after mutation\n      if (createUser.user) {\n        cache.modify({\n          fields: {\n            users(existing = []) {\n              const newRef = cache.writeFragment({\n                data: createUser.user,\n                fragment: gql`\n                  fragment NewUser on User {\n                    id\n                    name\n                    email\n                  }\n                `\n              });\n              return [...existing, newRef];\n            }\n          }\n        });\n      }\n    }\n  });\n}\n\n### Code Generation\n\nType-safe operations from schema\n\n**When to use**: TypeScript projects\n\n# GRAPHQL CODEGEN:\n\n\"\"\"\nGenerate TypeScript types from your schema and operations.\nNo more manually typing query responses.\n\"\"\"\n\n# Install\nnpm install -D @graphql-codegen\u002Fcli\nnpm install -D @graphql-codegen\u002Ftypescript\nnpm install -D @graphql-codegen\u002Ftypescript-operations\nnpm install -D @graphql-codegen\u002Ftypescript-react-apollo\n\n# codegen.ts\nimport type { CodegenConfig } from '@graphql-codegen\u002Fcli';\n\nconst config: CodegenConfig = {\n  schema: 'http:\u002F\u002Flocalhost:4000\u002Fgraphql',\n  documents: ['src\u002F**\u002F*.graphql', 'src\u002F**\u002F*.tsx'],\n  generates: {\n    '.\u002Fsrc\u002Fgenerated\u002Fgraphql.ts': {\n      plugins: [\n        'typescript',\n        'typescript-operations',\n        'typescript-react-apollo'\n      ],\n      config: {\n        withHooks: true,\n        withComponent: false\n      }\n    }\n  }\n};\n\nexport default config;\n\n# Run generation\nnpx graphql-codegen\n\n# Usage - fully typed!\nimport { useGetUserQuery, useCreateUserMutation } from '.\u002Fgenerated\u002Fgraphql';\n\nfunction UserProfile({ userId }: { userId: string }) {\n  const { data, loading } = useGetUserQuery({\n    variables: { id: userId }  \u002F\u002F Type-checked!\n  });\n\n  \u002F\u002F data.user is fully typed\n  return \u003Cdiv>{data?.user?.name}\u003C\u002Fdiv>;\n}\n\n### Error Handling with Unions\n\nExpected errors as data, not exceptions\n\n**When to use**: Operations that can fail in expected ways\n\n# ERRORS AS DATA:\n\n\"\"\"\nUse union types for expected failure cases.\nGraphQL errors are for unexpected failures.\n\"\"\"\n\n# Schema\ntype Mutation {\n  login(email: String!, password: String!): LoginResult!\n}\n\nunion LoginResult = LoginSuccess | InvalidCredentials | AccountLocked\n\ntype LoginSuccess {\n  user: User!\n  token: String!\n}\n\ntype InvalidCredentials {\n  message: String!\n}\n\ntype AccountLocked {\n  message: String!\n  unlockAt: DateTime\n}\n\n# Resolver\nconst resolvers = {\n  Mutation: {\n    login: async (_, { email, password }, { db }) => {\n      const user = await db.user.findByEmail(email);\n\n      if (!user || !await verifyPassword(password, user.hash)) {\n        return {\n          __typename: 'InvalidCredentials',\n          message: 'Invalid email or password'\n        };\n      }\n\n      if (user.lockedUntil && user.lockedUntil > new Date()) {\n        return {\n          __typename: 'AccountLocked',\n          message: 'Account temporarily locked',\n          unlockAt: user.lockedUntil\n        };\n      }\n\n      return {\n        __typename: 'LoginSuccess',\n        user,\n        token: generateToken(user)\n      };\n    }\n  },\n\n  LoginResult: {\n    __resolveType(obj) {\n      return obj.__typename;\n    }\n  }\n};\n\n# Client query\nconst LOGIN = gql`\n  mutation Login($email: String!, $password: String!) {\n    login(email: $email, password: $password) {\n      ... on LoginSuccess {\n        user { id name }\n        token\n      }\n      ... on InvalidCredentials {\n        message\n      }\n      ... on AccountLocked {\n        message\n        unlockAt\n      }\n    }\n  }\n`;\n\n\u002F\u002F Handle all cases\nconst result = data.login;\nswitch (result.__typename) {\n  case 'LoginSuccess':\n    setToken(result.token);\n    redirect('\u002Fdashboard');\n    break;\n  case 'InvalidCredentials':\n    setError(result.message);\n    break;\n  case 'AccountLocked':\n    setError(`${result.message}. Try again at ${result.unlockAt}`);\n    break;\n}\n\n## Sharp Edges\n\n### Each resolver makes separate database queries\n\nSeverity: CRITICAL\n\nSituation: You write resolvers that fetch data individually. A query for\n10 posts with authors makes 11 database queries. For 100 posts,\nthat's 101 queries. Response time becomes seconds.\n\nSymptoms:\n- Slow API responses\n- Many similar database queries in logs\n- Performance degrades with list size\n\nWhy this breaks:\nGraphQL resolvers run independently. Without batching, the author\nresolver runs separately for each post. The database gets hammered\nwith repeated similar queries.\n\nRecommended fix:\n\n# USE DATALOADER\n\nimport DataLoader from 'dataloader';\n\n\u002F\u002F Create loader per request\nconst userLoader = new DataLoader(async (ids) => {\n  const users = await db.user.findMany({\n    where: { id: { in: ids } }\n  });\n  \u002F\u002F IMPORTANT: Return in same order as input ids\n  const userMap = new Map(users.map(u => [u.id, u]));\n  return ids.map(id => userMap.get(id));\n});\n\n\u002F\u002F Use in resolver\nconst resolvers = {\n  Post: {\n    author: (post, _, { loaders }) =>\n      loaders.userLoader.load(post.authorId)\n  }\n};\n\n# Key points:\n# 1. Create new loaders per request (for caching scope)\n# 2. Return results in same order as input IDs\n# 3. Handle missing items (return null, not skip)\n\n### Deeply nested queries can DoS your server\n\nSeverity: CRITICAL\n\nSituation: Your schema has circular relationships (user.posts.author.posts...).\nA client sends a query 20 levels deep. Your server tries to resolve\nit and either times out or crashes.\n\nSymptoms:\n- Server timeouts on certain queries\n- Memory exhaustion\n- Slow response for nested queries\n\nWhy this breaks:\nGraphQL allows clients to request any valid query shape. Without\nlimits, a malicious or buggy client can craft queries that require\nexponential work. Even legitimate queries can accidentally be too deep.\n\nRecommended fix:\n\n# LIMIT QUERY DEPTH AND COMPLEXITY\n\nimport depthLimit from 'graphql-depth-limit';\nimport { createComplexityLimitRule } from 'graphql-validation-complexity';\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [\n    \u002F\u002F Limit nesting depth\n    depthLimit(10),\n\n    \u002F\u002F Limit query complexity\n    createComplexityLimitRule(1000, {\n      scalarCost: 1,\n      objectCost: 2,\n      listFactor: 10\n    })\n  ]\n});\n\n# Also consider:\n# - Query timeout limits\n# - Rate limiting per client\n# - Persisted queries (only allow pre-registered queries)\n\n### Introspection enabled in production exposes your schema\n\nSeverity: HIGH\n\nSituation: You deploy to production with introspection enabled. Anyone can\nquery your schema, discover all types, mutations, and field names.\nAttackers know exactly what to target.\n\nSymptoms:\n- Schema visible via introspection query\n- GraphQL Playground accessible in production\n- Full type information exposed\n\nWhy this breaks:\nIntrospection is essential for development and tooling, but in\nproduction it's a roadmap for attackers. They can find admin\nmutations, internal fields, and deprecated but still working APIs.\n\nRecommended fix:\n\n# DISABLE INTROSPECTION IN PRODUCTION\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  introspection: process.env.NODE_ENV !== 'production',\n  plugins: [\n    process.env.NODE_ENV === 'production'\n      ? ApolloServerPluginLandingPageDisabled()\n      : ApolloServerPluginLandingPageLocalDefault()\n  ]\n});\n\n# Better: Use persisted queries\n# Only allow pre-registered queries in production\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  persistedQueries: {\n    cache: new InMemoryLRUCache()\n  }\n});\n\n### Authorization only in schema directives, not resolvers\n\nSeverity: HIGH\n\nSituation: You rely entirely on @auth directives for authorization. Someone\nfinds a way around the directive, or complex business rules don't\nfit in a simple directive. Authorization fails.\n\nSymptoms:\n- Unauthorized access to data\n- Business rules not enforced\n- Directive-only security bypassed\n\nWhy this breaks:\nDirectives are good for simple checks but can't handle complex\nbusiness logic. \"User can edit their own posts, or any post in\ngroups they moderate\" doesn't fit in a directive.\n\nRecommended fix:\n\n# AUTHORIZE IN RESOLVERS\n\n\u002F\u002F Simple check in resolver\nMutation: {\n  deletePost: async (_, { id }, { user, db }) => {\n    if (!user) {\n      throw new AuthenticationError('Must be logged in');\n    }\n\n    const post = await db.post.findUnique({ where: { id } });\n\n    if (!post) {\n      throw new NotFoundError('Post not found');\n    }\n\n    \u002F\u002F Business logic authorization\n    const canDelete =\n      post.authorId === user.id ||\n      user.role === 'ADMIN' ||\n      await userModeratesGroup(user.id, post.groupId);\n\n    if (!canDelete) {\n      throw new ForbiddenError('Cannot delete this post');\n    }\n\n    return db.post.delete({ where: { id } });\n  }\n}\n\n\u002F\u002F Helper for field-level authorization\nUser: {\n  email: (user, _, { currentUser }) => {\n    \u002F\u002F Only show email to self or admin\n    if (currentUser?.id === user.id || currentUser?.role === 'ADMIN') {\n      return user.email;\n    }\n    return null;\n  }\n}\n\n### Authorization on queries but not on fields\n\nSeverity: HIGH\n\nSituation: You check if a user can access a resource, but not individual\nfields. User A can see User B's public profile, and accidentally\nalso sees their private email and phone number.\n\nSymptoms:\n- Sensitive data exposed\n- Privacy violations\n- Field data visible to wrong users\n\nWhy this breaks:\nField resolvers run after the parent is returned. If the parent\nquery returns a user, all fields are resolved - including sensitive\nones. Each sensitive field needs its own auth check.\n\nRecommended fix:\n\n# FIELD-LEVEL AUTHORIZATION\n\nconst resolvers = {\n  User: {\n    \u002F\u002F Public fields - no check needed\n    id: (user) => user.id,\n    name: (user) => user.name,\n\n    \u002F\u002F Private fields - check access\n    email: (user, _, { currentUser }) => {\n      if (!currentUser) return null;\n      if (currentUser.id === user.id) return user.email;\n      if (currentUser.role === 'ADMIN') return user.email;\n      return null;\n    },\n\n    phoneNumber: (user, _, { currentUser }) => {\n      if (currentUser?.id !== user.id) return null;\n      return user.phoneNumber;\n    },\n\n    \u002F\u002F Or throw instead of returning null\n    privateData: (user, _, { currentUser }) => {\n      if (currentUser?.id !== user.id) {\n        throw new ForbiddenError('Not authorized');\n      }\n      return user.privateData;\n    }\n  }\n};\n\n### Non-null field failure nullifies entire parent\n\nSeverity: MEDIUM\n\nSituation: You make fields non-null for convenience. A resolver throws or\nreturns null. The error propagates up, nullifying parent objects,\nuntil the whole query response is null or errors out.\n\nSymptoms:\n- Queries return null unexpectedly\n- One error affects unrelated fields\n- Partial data can't be returned\n\nWhy this breaks:\nGraphQL's null propagation means if a non-null field can't resolve,\nits parent becomes null. If that parent is also non-null, it\npropagates further. One failing field can break an entire response.\n\nRecommended fix:\n\n# DESIGN NULLABILITY INTENTIONALLY\n\n# WRONG: Everything non-null\ntype User {\n  id: ID!\n  name: String!\n  email: String!\n  avatar: String!      # What if no avatar?\n  lastLogin: DateTime! # What if never logged in?\n}\n\n# RIGHT: Nullable where appropriate\ntype User {\n  id: ID!              # Always exists\n  name: String!        # Required field\n  email: String!       # Required field\n  avatar: String       # Optional - may not exist\n  lastLogin: DateTime  # Nullable - may be null\n}\n\n# For lists:\n# [User!]! - Non-null list of non-null users (recommended)\n# [User!]  - Nullable list of non-null users\n# [User]!  - Non-null list of nullable users (rarely useful)\n# [User]   - Nullable list of nullable users (avoid)\n\n# Rule of thumb:\n# - Non-null if always present and failure should fail query\n# - Nullable if optional or failure shouldn't break response\n\n### Expensive queries treated same as cheap ones\n\nSeverity: MEDIUM\n\nSituation: Every query is processed the same. A simple user(id) query uses\nthe same resources as users(first: 1000) { posts { comments } }.\nExpensive queries starve out cheap ones.\n\nSymptoms:\n- Expensive queries slow everything\n- No way to prioritize queries\n- Rate limiting is ineffective\n\nWhy this breaks:\nNot all GraphQL operations are equal. Fetching 1000 users with\nnested data is orders of magnitude more expensive than fetching\none user. Without cost analysis, you can't rate limit properly.\n\nRecommended fix:\n\n# QUERY COST ANALYSIS\n\nimport { createComplexityLimitRule } from 'graphql-validation-complexity';\n\n\u002F\u002F Define complexity per field\nconst complexityRules = createComplexityLimitRule(1000, {\n  scalarCost: 1,\n  objectCost: 10,\n  listFactor: 10,\n  \u002F\u002F Custom field costs\n  fieldCost: {\n    'Query.searchUsers': 100,\n    'Query.analytics': 500,\n    'User.posts': ({ args }) => args.limit || 10\n  }\n});\n\n\u002F\u002F For rate limiting by cost\nconst costPlugin = {\n  requestDidStart() {\n    return {\n      didResolveOperation({ request, document }) {\n        const cost = calculateQueryCost(document);\n        if (cost > 1000) {\n          throw new Error(`Query too expensive: ${cost}`);\n        }\n        \u002F\u002F Track cost for rate limiting\n        rateLimiter.consume(request.userId, cost);\n      }\n    };\n  }\n};\n\n### Subscriptions not properly cleaned up\n\nSeverity: MEDIUM\n\nSituation: Clients subscribe but don't unsubscribe cleanly. Network issues\nleave orphaned subscriptions. Server memory grows as dead\nsubscriptions accumulate.\n\nSymptoms:\n- Memory usage grows over time\n- Dead connections accumulate\n- Server slows down\n\nWhy this breaks:\nEach subscription holds server resources. Without proper cleanup\non disconnect, resources accumulate. Long-running servers\neventually run out of memory.\n\nRecommended fix:\n\n# PROPER SUBSCRIPTION CLEANUP\n\nimport { PubSub, withFilter } from 'graphql-subscriptions';\nimport { WebSocketServer } from 'ws';\nimport { useServer } from 'graphql-ws\u002Flib\u002Fuse\u002Fws';\n\nconst pubsub = new PubSub();\n\n\u002F\u002F Track active subscriptions\nconst activeSubscriptions = new Map();\n\nconst wsServer = new WebSocketServer({\n  server: httpServer,\n  path: '\u002Fgraphql'\n});\n\nuseServer({\n  schema,\n  context: (ctx) => ({\n    pubsub,\n    userId: ctx.connectionParams?.userId\n  }),\n  onConnect: (ctx) => {\n    console.log('Client connected');\n  },\n  onDisconnect: (ctx) => {\n    \u002F\u002F Clean up resources for this connection\n    const userId = ctx.connectionParams?.userId;\n    activeSubscriptions.delete(userId);\n  }\n}, wsServer);\n\n\u002F\u002F Subscription resolver with cleanup\nSubscription: {\n  messageReceived: {\n    subscribe: withFilter(\n      (_, { roomId }, { pubsub, userId }) => {\n        \u002F\u002F Track subscription\n        activeSubscriptions.set(userId, roomId);\n        return pubsub.asyncIterator(`ROOM_${roomId}`);\n      },\n      (payload, { roomId }) => {\n        return payload.roomId === roomId;\n      }\n    )\n  }\n}\n\n## Validation Checks\n\n### Introspection enabled in production\n\nSeverity: WARNING\n\nMessage: Introspection should be disabled in production\n\nFix action: Set introspection: process.env.NODE_ENV !== 'production'\n\n### Direct database query in resolver\n\nSeverity: WARNING\n\nMessage: Consider using DataLoader to batch and cache queries\n\nFix action: Create DataLoader and use .load() instead of direct query\n\n### No query depth limiting\n\nSeverity: WARNING\n\nMessage: Consider adding depth limiting to prevent DoS\n\nFix action: Add validationRules: [depthLimit(10)]\n\n### Resolver without try-catch\n\nSeverity: INFO\n\nMessage: Consider wrapping resolver logic in try-catch\n\nFix action: Add error handling to provide better error messages\n\n### JSON or Any type in schema\n\nSeverity: INFO\n\nMessage: Avoid JSON\u002FAny types - they bypass GraphQL's type safety\n\nFix action: Define proper input\u002Foutput types\n\n### Mutation returns bare type instead of payload\n\nSeverity: INFO\n\nMessage: Consider using payload types for mutations (includes errors)\n\nFix action: Create CreateUserPayload type with user and errors fields\n\n### List field without pagination arguments\n\nSeverity: INFO\n\nMessage: List fields should have pagination (limit, first, after)\n\nFix action: Add arguments: field(limit: Int, offset: Int): [Type!]!\n\n### Query hook without error handling\n\nSeverity: INFO\n\nMessage: Handle query errors in UI\n\nFix action: Destructure and handle error: const { error } = useQuery(...)\n\n### Using refetch instead of cache update\n\nSeverity: INFO\n\nMessage: Consider cache update instead of refetch for better UX\n\nFix action: Use update function to modify cache directly\n\n## Collaboration\n\n### Delegation Triggers\n\n- user needs database optimization -> postgres-wizard (Optimize queries for GraphQL resolvers)\n- user needs authentication system -> authentication-oauth (Auth for GraphQL context)\n- user needs caching layer -> caching-strategies (Response caching, DataLoader caching)\n- user needs real-time infrastructure -> backend (WebSocket setup for subscriptions)\n\n## Related Skills\n\nWorks well with: `backend`, `postgres-wizard`, `nextjs-app-router`, `react-patterns`\n\n## When to Use\n- User mentions or implies: graphql\n- User mentions or implies: graphql schema\n- User mentions or implies: graphql resolver\n- User mentions or implies: apollo server\n- User mentions or implies: apollo client\n- User mentions or implies: graphql federation\n- User mentions or implies: dataloader\n- User mentions or implies: graphql codegen\n- User mentions or implies: graphql query\n- User mentions or implies: graphql mutation\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,222,502,"2026-05-16 13:21:22",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"5ad85be4-347a-475c-8057-7337e5dfeb8a","1.0.0","graphql.zip",9043,"uploads\u002Fskills\u002F92fbc2d1-4f86-4622-915d-15c85ac42d18\u002Fgraphql.zip","fbfe480f075e150f4da505942889a542753302ce4e939674ce229b8914d9ad4e","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":25808}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]