Skip to main content
command CX Codex

implement-graphql-api · davepoon — Claude Code command: what it does

implement-graphql-api walks an agent through building a GraphQL API: server setup, SDL schema, types, cursor pagination, root Query and Mutation fields.

MIT ★ 3,785 updated 2026-10-25

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude
Open on GitHub

What implement-graphql-api does

The command takes an agent through the stages of a GraphQL build: bring up a server on Apollo Server or something similar, choose schema-first or code-first, write the types, then fill in the root Query and Mutation. The SDL skeleton ships with custom scalars (DateTime, EmailAddress, PhoneNumber, JSON, Upload) plus enums for roles and statuses.

Shop shapes are already drawn: User with a nested profile, Product with images and variants, Order with line items and shipping and billing addresses. Paging is cursor-based, so every list returns a connection with edges, pageInfo and totalCount. An offset-style API means rewriting those types by hand, since only one paging style is covered.

Input types like CreateUserInput, ProductFilters and CreateProductInput carry defaults inline, such as role: USER and status: DRAFT. Auth mutations come first: login, logout, refreshToken, forgotPassword. Read the output as scaffolding; business logic still needs writing. The server step names Apollo Server, so have that package in the project before starting.

What it helps with

  • Draft a shop schema covering products, orders and addresses
  • Add cursor pagination to a product list
  • Define input types for creating and updating users
  • Wire up login and token refresh mutations
  • Declare custom scalars for email and phone

Example prompts for the agent

  • Build the GraphQL API for the product catalog: schema, types, Query and Mutation
  • Set up Apollo Server and write the SDL for users and orders
  • Add cursor pagination to the orders query

How to install implement-graphql-api

1Plugin marketplace

/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude

2Manually: put the files in place

.claude/commands/implement-graphql-api.md

Call it with /implement-graphql-api. For all projects use ~/.claude/commands/

Questions about implement-graphql-api

How do I install implement-graphql-api in Claude Code?

Add the marketplace with /plugin marketplace add davepoon/buildwithclaude, then run /plugin install all-commands@buildwithclaude.

What does implement-graphql-api do?

It guides an agent from GraphQL server setup to a schema with object types, input types, root Query and Mutation fields.

Is the paging cursor-based or offset-based?

Cursor-based. Lists return connection types with edges, pageInfo and totalCount; there is no offset variant in the skeleton.

Source text

implement-graphql-api.md · MIT
---
description: Implement GraphQL API endpoints
category: api-development
---

# Implement GraphQL API

Implement GraphQL API endpoints

## Instructions

1. **GraphQL Setup and Configuration**
   - Set up GraphQL server with Apollo Server or similar
   - Configure schema-first or code-first approach
   - Plan GraphQL architecture and data modeling
   - Set up development tools and introspection
   - Configure GraphQL playground and documentation

2. **Schema Definition and Type System**
   - Define comprehensive GraphQL schema:

   **Schema Definition (SDL):**
   ```graphql
   # schema/schema.graphql
   
   # Scalar types
   scalar DateTime
   scalar EmailAddress
   scalar PhoneNumber
   scalar JSON
   scalar Upload

   # User types and enums
   enum UserRole {
     USER
     ADMIN
     MANAGER
   }

   enum UserStatus {
     ACTIVE
     INACTIVE
     SUSPENDED
     PENDING_VERIFICATION
   }

   type User {
     id: ID!
     email: EmailAddress!
     username: String!
     firstName: String!
     lastName: String!
     fullName: String!
     phone: PhoneNumber
     dateOfBirth: DateTime
     avatar: String
     role: UserRole!
     status: UserStatus!
     emailVerified: Boolean!
     phoneVerified: Boolean!
     profile: UserProfile
     orders(
       first: Int = 10
       after: String
       status: OrderStatus
     ): OrderConnection!
     createdAt: DateTime!
     updatedAt: DateTime!
     lastLoginAt: DateTime
   }

   type UserProfile {
     bio: String
     website: String
     location: String
     timezone: String!
     language: String!
     notificationPreferences: JSON!
     privacySettings: JSON!
   }

   # Product types
   enum ProductStatus {
     DRAFT
     ACTIVE
     INACTIVE
     ARCHIVED
   }

   enum ProductVisibility {
     VISIBLE
     HIDDEN
     CATALOG_ONLY
     SEARCH_ONLY
   }

   type Product {
     id: ID!
     name: String!
     slug: String!
     sku: String!
     description: String
     shortDescription: String
     price: Float!
     comparePrice: Float
     costPrice: Float
     weight: Float
     dimensions: ProductDimensions
     category: Category
     brand: Brand
     vendor: Vendor
     status: ProductStatus!
     visibility: ProductVisibility!
     inventoryTracking: Boolean!
     inventoryQuantity: Int
     lowStockThreshold: Int
     allowBackorder: Boolean!
     requiresShipping: Boolean!
     isDigital: Boolean!
     featured: Boolean!
     tags: [String!]!
     attributes: JSON!
     images: [ProductImage!]!
     variants: [ProductVariant!]!
     reviews(
       first: Int = 10
       after: String
       rating: Int
     ): ReviewConnection!
     averageRating: Float
     reviewCount: Int!
     createdAt: DateTime!
     updatedAt: DateTime!
     publishedAt: DateTime
   }

   type ProductDimensions {
     length: Float
     width: Float
     height: Float
     unit: String!
   }

   type ProductImage {
     id: ID!
     url: String!
     altText: String
     sortOrder: Int!
   }

   type ProductVariant {
     id: ID!
     sku: String!
     price: Float!
     comparePrice: Float
     inventoryQuantity: Int
     attributes: JSON!
     image: ProductImage
   }

   # Order types
   enum OrderStatus {
     PENDING
     PROCESSING
     SHIPPED
     DELIVERED
     CANCELLED
     REFUNDED
     ON_HOLD
   }

   type Order {
     id: ID!
     orderNumber: String!
     user: User
     status: OrderStatus!
     currency: String!
     subtotal: Float!
     taxTotal: Float!
     shippingTotal: Float!
     discountTotal: Float!
     total: Float!
     billingAddress: Address!
     shippingAddress: Address!
     shippingMethod: String
     trackingNumber: String
     items: [OrderItem!]!
     notes: String
     createdAt: DateTime!
     updatedAt: DateTime!
     shippedAt: DateTime
     deliveredAt: DateTime
   }

   type OrderItem {
     id: ID!
     product: Product!
     productVariant: ProductVariant
     quantity: Int!
     unitPrice: Float!
     totalPrice: Float!
     productName: String!
     productSku: String!
     productAttributes: JSON
   }

   type Address {
     firstName: String!
     lastName: String!
     company: String
     addressLine1: String!
     addressLine2: String
     city: String!
     state: String
     postalCode: String!
     country: String!
     phone: PhoneNumber
   }

   # Connection types for pagination
   type UserConnection {
     edges: [UserEdge!]!
     pageInfo: PageInfo!
     totalCount: Int!
   }

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

   type ProductConnection {
     edges: [ProductEdge!]!
     pageInfo: PageInfo!
     totalCount: Int!
   }

   type ProductEdge {
     node: Product!
     cursor: String!
   }

   type OrderConnection {
     edges: [OrderEdge!]!
     pageInfo: PageInfo!
     totalCount: Int!
   }

   type OrderEdge {
     node: Order!
     cursor: String!
   }

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

   # Input types
   input CreateUserInput {
     email: EmailAddress!
     password: String!
     firstName: String!
     lastName: String!
     phone: PhoneNumber
     dateOfBirth: DateTime
     role: UserRole = USER
   }

   input UpdateUserInput {
     email: EmailAddress
     firstName: String
     lastName: String
     phone: PhoneNumber
     dateOfBirth: DateTime
     status: UserStatus
   }

   input ProductFilters {
     category: ID
     brand: ID
     priceMin: Float
     priceMax: Float
     status: ProductStatus
     featured: Boolean
     inStock: Boolean
     tags: [String!]
     search: String
   }

   input CreateProductInput {
     name: String!
     slug: String!
     sku: String!
     description: String
     price: Float!
     comparePrice: Float
     categoryId: ID
     brandId: ID
     status: ProductStatus = DRAFT
     inventoryQuantity: Int = 0
     attributes: JSON
     tags: [String!]
   }

   # Root types
   type Query {
     # User queries
     me: User
     user(id: ID!): User
     users(
       first: Int = 10
       after: String
       search: String
       role: UserRole
       status: UserStatus
     ): UserConnection!

     # Product queries
     product(id: ID, slug: String): Product
     products(
       first: Int = 10
       after: String
       filters: ProductFilters
       sortBy: ProductSortBy = CREATED_AT
       sortOrder: SortOrder = DESC
     ): ProductConnection!

     # Order queries
     order(id: ID!): Order
     orders(
       first: Int = 10
       after: String
       status: OrderStatus
       userId: ID
     ): OrderConnection!

     # Search
     search(
       query: String!
       first: Int = 10
       after: String
       types: [SearchType!] = [USER, PRODUCT, ORDER]
     ): SearchConnection!
   }

   type Mutation {
     # Auth mutations
     login(email: EmailAddress!, password: String!): AuthPayload!
     logout: Boolean!
     refreshToken: AuthPayload!
     forgotPassword(email: EmailAddress!): Boolean!
     resetPassword(token: String!, password: String!): AuthPayload!

     # User mutations
     createUser(input: CreateUserInput!): User!
     updateUser(id: ID!, input: UpdateUserInput!): User!
     deleteUser(id: ID!): Boolean!
     updateProfile(input: UpdateProfileInput!): UserProfile!

     # Product mutations
     createProduct(input: CreateProductInput!): Product!
     updateProduct(id: ID!, input: UpdateProductInput!): Product!
     deleteProduct(id: ID!): Boolean!
     uploadProductImage(productId: ID!, file: Upload!): ProductImage!

     # Order mutations
     createOrder(input: CreateOrderInput!): Order!
     updateOrderStatus(id: ID!, status: OrderStatus!): Order!
     addOrderItem(orderId: ID!, input: AddOrderItemInput!): OrderItem!
     removeOrderItem(id: ID!): Boolean!
   }

   type Subscription {
     # Real-time updates
     orderUpdated(userId: ID): Order!
     productUpdated(productId: ID): Product!
     userStatusChanged(userId: ID): User!
     
     # Admin subscriptions
     newOrder: Order!
     lowStockAlert: Product!
   }

   enum ProductSortBy {
     CREATED_AT
     NAME
     PRICE
     RATING
     POPULARITY
   }

   enum SortOrder {
     ASC
     DESC
   }

   enum SearchType {
     USER
     PRODUCT
     ORDER
   }

   type AuthPayload {
     token: String!
     refreshToken: String!
     user: User!
     expiresAt: DateTime!
   }
   ```

3. **Resolver Implementation**
   - Implement comprehensive resolvers:

   **Main Resolvers:**
   ```javascript
   // resolvers/index.js
   const { GraphQLDateTime } = require('graphql-iso-date');
   const { GraphQLEmailAddress, GraphQLPhoneNumber } = require('graphql-scalars');
   const GraphQLJSON = require('graphql-type-json');
   const GraphQLUpload = require('graphql-upload/GraphQLUpload.js');

   const userResolvers = require('./userResolvers');
   const productResolvers = require('./productResolvers');
   const orderResolvers = require('./orderResolvers');
   const searchResolvers = require('./searchResolvers');

   const resolvers = {
     // Custom scalars
     DateTime: GraphQLDateTime,
     EmailAddress: GraphQLEmailAddress,
     PhoneNumber: GraphQLPhoneNumber,
     JSON: GraphQLJSON,
     Upload: GraphQLUpload,

     // Root resolvers
     Query: {
       ...userResolvers.Query,
       ...productResolvers.Query,
       ...orderResolvers.Query,
       ...searchResolvers.Query
     },

     Mutation: {
       ...userResolvers.Mutation,
       ...productResolvers.Mutation,
       ...orderResolvers.Mutation
     },

     Subscription: {
       ...userResolvers.Subscription,
       ...productResolvers.Subscription,
       ...orderResolvers.Subscription
     },

     // Type resolvers
     User: userResolvers.User,
     Product: productResolvers.Product,
     Order: orderResolvers.Order
   };

   module.exports = resolvers;
   ```

   **User Resolvers:**
   ```javascript
   // resolvers/userResolvers.js
   const { AuthenticationError, ForbiddenError, UserInputError } = require('apollo-server-express');
   const { withFilter } = require('graphql-subscriptions');
   const userService = require('../services/userService');
   const { requireAuth, requireRole } = require('../utils/authHelpers');
   const { createConnectionFromArray } = require('../utils/connectionHelpers');

   const userResolvers = {
     Query: {
       async me(parent, args, context) {
         requireAuth(context);
         return await userService.findById(context.user.id);
       },

       async user(parent, { id }, context) {
         requireAuth(context);
         
         const user = await userService.findById(id);
         if (!user) {
           throw new UserInputError('User not found');
         }

         // Privacy check - users can only see their own data unless admin
         if (context.user.id !== user.id && !['admin', 'manager'].includes(context.user.role)) {
           throw new ForbiddenError('Insufficient permissions');
         }

         return user;
       },

       async users(parent, { first, after, search, role, status }, context) {
         requireAuth(context);
         requireRole(context, ['admin', 'manager']);

         const result = await userService.findUsers({
           first,
           after,
           search,
           role,
           status
         });

         return createConnectionFromArray(result.users, {
           first,
           after,
           totalCount: result.totalCount
         });
       }
     },

     Mutation: {
       async createUser(parent, { input }, context) {
         requireAuth(context);
         requireRole(context, ['admin']);

         // Check for existing user
         const existingUser = await userService.findByEmail(input.email);
         if (existingUser) {
           throw new UserInputError('User with this email already exists');
         }

         const user = await userService.createUser(input);
         
         // Publish subscription for real-time updates
         context.pubsub.publish('USER_CREATED', { userCreated: user });
         
         return user;
       },

       async updateUser(parent, { id, input }, context) {
         requireAuth(context);
         
         const existingUser = await userService.findById(id);
         if (!existingUser) {
           throw new UserInputError('User not found');
         }

         // Authorization check
         if (context.user.id !== id && !['admin', 'manager'].includes(context.user.role)) {
           throw new ForbiddenError('Insufficient permissions');
         }

         // Role change restriction
         if (input.role && !['admin'].includes(context.user.role)) {
           throw new ForbiddenError('Insufficient permissions to change user role');
         }

         const updatedUser = await userService.updateUser(id, input);
         
         // Publish subscription
         context.pubsub.publish('USER_UPDATED', { userUpdated: updatedUser });
         
         return updatedUser;
       },

       async deleteUser(parent, { id }, context) {
         requireAuth(context);
         requireRole(context, ['admin']);

         // Prevent self-deletion
         if (context.user.id === id) {
           throw new UserInputError('Cannot delete your own account');
         }

         const existingUser = await userService.findById(id);
         if (!existingUser) {
           throw new UserInputError('User not found');
         }

         await userService.deleteUser(id);
         
         // Publish subscription
         context.pubsub.publish('USER_DELETED', { userDeleted: existingUser });
         
         return true;
       }
     },

     Subscription: {
       userStatusChanged: {
         subscribe: withFilter(
           (parent, args, context) => {
             requireAuth(context);
             return context.pubsub.asyncIterator(['USER_UPDATED']);
           },
           (payload, variables) => {
             // Filter by userId if provided
             return !variables.userId || payload.userUpdated.id === variables.userId;
           }
         )
       }
     },

     // Field resolvers
     User: {
       fullName(parent) {
         return `${parent.firstName} ${parent.lastName}`;
       },

       async profile(parent, args, context) {
         return await userService.getUserProfile(parent.id);
       },

       async orders(parent, { first, after, status }, context) {
         requireAuth(context);
         
         // Users can only see their own orders unless admin
         if (context.user.id !== parent.id && !['admin', 'manager'].includes(context.user.role)) {
           throw new ForbiddenError('Insufficient permissions');
         }

         const result = await userService.getUserOrders(parent.id, {
           first,
           after,
           status
         });

         return createConnectionFromArray(result.orders, {
           first,
           after,
           totalCount: result.totalCount
         });
       }
     }
   };

   module.exports = userResolvers;
   ```

4. **DataLoader for N+1 Problem**
   - Implement efficient data loading:

   **DataLoader Implementation:**
   ```javascript
   // dataLoaders/index.js
   const DataLoader = require('dataloader');
   const userService = require('../services/userService');
   const productService = require('../services/productService');
   const orderService = require('../services/orderService');

   class DataLoaders {
     constructor() {
       this.userLoader = new DataLoader(
         async (userIds) => {
           const users = await userService.findByIds(userIds);
           return userIds.map(id => users.find(user => user.id === id) || null);
         },
         {
           cacheKeyFn: (key) => key.toString(),
           maxBatchSize: 100
         }
       );

       this.userProfileLoader = new DataLoader(
         async (userIds) => {
           const profiles = await userService.getProfilesByUserIds(userIds);
           return userIds.map(id => profiles.find(profile => profile.userId === id) || null);
         }
       );

       this.productLoader = new DataLoader(
         async (productIds) => {
           const products = await productService.findByIds(productIds);
           return productIds.map(id => products.find(product => product.id === id) || null);
         }
       );

       this.productCategoryLoader = new DataLoader(
         async (categoryIds) => {
           const categories = await productService.getCategoriesByIds(categoryIds);
           return categoryIds.map(id => categories.find(category => category.id === id) || null);
         }
       );

       this.productImagesLoader = new DataLoader(
         async (productIds) => {
           const imagesMap = await productService.getImagesByProductIds(productIds);
           return productIds.map(id => imagesMap[id] || []);
         }
       );

       this.orderItemsLoader = new DataLoader(
         async (orderIds) => {
           const itemsMap = await orderService.getItemsByOrderIds(orderIds);
           return orderIds.map(id => itemsMap[id] || []);
         }
       );

       this.productReviewsLoader = new DataLoader(
         async (productIds) => {
           const reviewsMap = await productService.getReviewsByProductIds(productIds);
           return productIds.map(id => reviewsMap[id] || []);
         }
       );
     }

     // Clear all caches
     clearAll() {
       this.userLoader.clearAll();
       this.userProfileLoader.clearAll();
       this.productLoader.clearAll();
       this.productCategoryLoader.clearAll();
       this.productImagesLoader.clearAll();
       this.orderItemsLoader.clearAll();
       this.productReviewsLoader.clearAll();
     }

     // Clear specific cache
     clearUser(userId) {
       this.userLoader.clear(userId);
       this.userProfileLoader.clear(userId);
     }

     clearProduct(productId) {
       this.productLoader.clear(productId);
       this.productImagesLoader.clear(productId);
       this.productReviewsLoader.clear(productId);
     }
   }

   module.exports = DataLoaders;
   ```

5. **Authentication and Authorization**
   - Implement GraphQL-specific auth:

   **Auth Helpers:**
   ```javascript
   // utils/authHelpers.js
   const { AuthenticationError, ForbiddenError } = require('apollo-server-express');
   const jwt = require('jsonwebtoken');
   const userService = require('../services/userService');

   class GraphQLAuth {
     static async getUser(req) {
       const authHeader = req.headers.authorization;
       
       if (!authHeader) {
         return null;
       }

       const token = authHeader.replace('Bearer ', '');
       
       try {
         const decoded = jwt.verify(token, process.env.JWT_SECRET);
         const user = await userService.findById(decoded.userId);
         
         if (!user || user.status !== 'active') {
           return null;
         }

         return user;
       } catch (error) {
         return null;
       }
     }

     static requireAuth(context) {
       if (!context.user) {
         throw new AuthenticationError('Authentication required');
       }
       return context.user;
     }

     static requireRole(context, roles) {
       this.requireAuth(context);
       
       if (!roles.includes(context.user.role)) {
         throw new ForbiddenError(`Requires one of the following roles: ${roles.join(', ')}`);
       }
       
       return context.user;
     }

     static requirePermission(context, permissions) {
       this.requireAuth(context);
       
       const userPermissions = context.user.permissions || [];
       const hasPermission = permissions.some(permission => 
         userPermissions.includes(permission)
       );
       
       if (!hasPermission) {
         throw new ForbiddenError(`Requires one of the following permissions: ${permissions.join(', ')}`);
       }
       
       return context.user;
     }

     static canAccessResource(context, resourceUserId, adminRoles = ['admin', 'manager']) {
       this.requireAuth(context);
       
       const isOwner = context.user.id === resourceUserId;
       const isAdmin = adminRoles.includes(context.user.role);
       
       if (!isOwner && !isAdmin) {
         throw new ForbiddenError('Insufficient permissions to access this resource');
       }
       
       return context.user;
     }
   }

   // Export individual functions for convenience
   const { requireAuth, requireRole, requirePermission, canAccessResource } = GraphQLAuth;

   module.exports = {
     GraphQLAuth,
     requireAuth,
     requireRole,
     requirePermission,
     canAccessResource
   };
   ```

6. **Real-time Subscriptions**
   - Implement GraphQL subscriptions:

   **Subscription Setup:**
   ```javascript
   // subscriptions/index.js
   const { PubSub } = require('graphql-subscriptions');
   const { RedisPubSub } = require('graphql-redis-subscriptions');
   const Redis = require('ioredis');

   // Use Redis for production, in-memory for development
   const createPubSub = () => {
     if (process.env.NODE_ENV === 'production') {
       const redisClient = new Redis(process.env.REDIS_URL);
       return new RedisPubSub({
         publisher: redisClient,
         subscriber: redisClient.duplicate()
       });
     } else {
       return new PubSub();
     }
   };

   const pubsub = createPubSub();

   // Subscription events
   const SUBSCRIPTION_EVENTS = {
     USER_CREATED: 'USER_CREATED',
     USER_UPDATED: 'USER_UPDATED',
     USER_DELETED: 'USER_DELETED',
     ORDER_CREATED: 'ORDER_CREATED',
     ORDER_UPDATED: 'ORDER_UPDATED',
     PRODUCT_UPDATED: 'PRODUCT_UPDATED',
     LOW_STOCK_ALERT: 'LOW_STOCK_ALERT'
   };

   // Subscription resolvers
   const subscriptionResolvers = {
     orderUpdated: {
       subscribe: (parent, { userId }, context) => {
         requireAuth(context);
         
         // Users can only subscribe to their own orders unless admin
         if (userId && context.user.id !== userId && !['admin', 'manager'].includes(context.user.role)) {
           throw new ForbiddenError('Insufficient permissions');
         }
         
         return pubsub.asyncIterator([SUBSCRIPTION_EVENTS.ORDER_UPDATED]);
       },
       resolve: (payload, { userId }) => {
         // Filter by userId if provided
         if (userId && payload.orderUpdated.userId !== userId) {
           return null;
         }
         return payload.orderUpdated;
       }
     },

     productUpdated: {
       subscribe: (parent, { productId }, context) => {
         return pubsub.asyncIterator([SUBSCRIPTION_EVENTS.PRODUCT_UPDATED]);
       },
       resolve: (payload, { productId }) => {
         // Filter by productId if provided
         if (productId && payload.productUpdated.id !== productId) {
           return null;
         }
         return payload.productUpdated;
       }
     },

     userStatusChanged: {
       subscribe: (parent, { userId }, context) => {
         requireAuth(context);
         requireRole(context, ['admin', 'manager']);
         
         return pubsub.asyncIterator([SUBSCRIPTION_EVENTS.USER_UPDATED]);
       },
       resolve: (payload, { userId }) => {
         if (userId && payload.userUpdated.id !== userId) {
           return null;
         }
         return payload.userUpdated;
       }
     },

     newOrder: {
       subscribe: (parent, args, context) => {
         requireAuth(context);
         requireRole(context, ['admin', 'manager']);
         
         return pubsub.asyncIterator([SUBSCRIPTION_EVENTS.ORDER_CREATED]);
       }
     },

     lowStockAlert: {
       subscribe: (parent, args, context) => {
         requireAuth(context);
         requireRole(context, ['admin', 'manager']);
         
         return pubsub.asyncIterator([SUBSCRIPTION_EVENTS.LOW_STOCK_ALERT]);
       }
     }
   };

   module.exports = {
     pubsub,
     SUBSCRIPTION_EVENTS,
     subscriptionResolvers
   };
   ```

7. **Error Handling and Validation**
   - Implement comprehensive error handling:

   **Error Handling:**
   ```javascript
   // utils/errorHandling.js
   const { 
     ApolloError, 
     AuthenticationError, 
     ForbiddenError, 
     UserInputError 
   } = require('apollo-server-express');

   class GraphQLErrorHandler {
     static handleError(error, operation) {
       // Log error for debugging
       console.error('GraphQL Error:', {
         message: error.message,
         operation: operation?.operationName,
         variables: operation?.variables,
         stack: error.stack
       });

       // Database errors
       if (error.code === '23505') { // Unique constraint violation
         return new UserInputError('A record with this information already exists');
       }
       
       if (error.code === '23503') { // Foreign key constraint violation
         return new UserInputError('Referenced record does not exist');
       }

       // Validation errors
       if (error.name === 'ValidationError') {
         const messages = Object.values(error.errors).map(err => err.message);
         return new UserInputError('Validation failed', {
           validationErrors: messages
         });
       }

       // Permission errors
       if (error.message.includes('permission') || error.message.includes('access')) {
         return new ForbiddenError(error.message);
       }

       // Authentication errors
       if (error.message.includes('token') || error.message.includes('auth')) {
         return new AuthenticationError(error.message);
       }

       // Network/external service errors
       if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
         return new ApolloError('External service unavailable', 'SERVICE_UNAVAILABLE');
       }

       // Default to internal error
       return new ApolloError(
         'An unexpected error occurred',
         'INTERNAL_ERROR',
         { originalError: error.message }
       );
     }

     static formatError(error) {
       // Don't expose internal errors in production
       if (process.env.NODE_ENV === 'production' && !error.extensions?.code) {
         return new ApolloError('Internal server error', 'INTERNAL_ERROR');
       }

       // Add request ID for tracking
       if (error.extensions?.requestId) {
         error.extensions.requestId = error.extensions.requestId;
       }

       return error;
     }
   }

   // Input validation helper
   class InputValidator {
     static validateEmail(email) {
       const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
       if (!emailRegex.test(email)) {
         throw new UserInputError('Invalid email format');
       }
     }

     static validatePassword(password) {
       if (password.length < 8) {
         throw new UserInputError('Password must be at least 8 characters long');
       }
       
       if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
         throw new UserInputError('Password must contain uppercase, lowercase, and numeric characters');
       }
     }

     static validatePhoneNumber(phone) {
       const phoneRegex = /^\+?[\d\s\-\(\)]{10,20}$/;
       if (!phoneRegex.test(phone)) {
         throw new UserInputError('Invalid phone number format');
       }
     }

     static validateRequired(value, fieldName) {
       if (!value || (typeof value === 'string' && !value.trim())) {
         throw new UserInputError(`${fieldName} is required`);
       }
     }

     static validateStringLength(value, fieldName, min = 0, max = 255) {
       if (typeof value !== 'string') {
         throw new UserInputError(`${fieldName} must be a string`);
       }
       
       if (value.length < min) {
         throw new UserInputError(`${fieldName} must be at least ${min} characters`);
       }
       
       if (value.length > max) {
         throw new UserInputError(`${fieldName} must not exceed ${max} characters`);
       }
     }

     static validateNumericRange(value, fieldName, min, max) {
       if (typeof value !== 'number' || isNaN(value)) {
         throw new UserInputError(`${fieldName} must be a valid number`);
       }
       
       if (min !== undefined && value < min) {
         throw new UserInputError(`${fieldName} must be at least ${min}`);
       }
       
       if (max !== undefined && value > max) {
         throw new UserInputError(`${fieldName} must not exceed ${max}`);
       }
     }
   }

   module.exports = {
     GraphQLErrorHandler,
     InputValidator
   };
   ```

8. **Performance Optimization**
   - Implement GraphQL performance optimizations:

   **Query Complexity and Depth Limiting:**
   ```javascript
   // utils/queryLimiting.js
   const depthLimit = require('graphql-depth-limit');
   const costAnalysis = require('graphql-query-complexity');

   class QueryLimiting {
     static createDepthLimit(maxDepth = 10) {
       return depthLimit(maxDepth, {
         ignoreIntrospection: true
       });
     }

     static createComplexityAnalysis(maxComplexity = 1000) {
       return costAnalysis({
         maximumComplexity: maxComplexity,
         introspection: true,
         scalarCost: 1,
         objectCost: 1,
         listFactor: 10,
         fieldExtensions: {
           complexity: (options) => {
             // Custom complexity calculation
             const { args, childComplexity } = options;
             
             // List fields have higher complexity
             if (args.first) {
               return childComplexity * Math.min(args.first, 100);
             }
             
             return childComplexity;
           }
         },
         createError: (max, actual) => {
           return new Error(`Query complexity ${actual} exceeds maximum allowed complexity ${max}`);
         }
       });
     }

     static createQueryTimeout(timeout = 30000) {
       return {
         willSendResponse(requestContext) {
           if (requestContext.request.query) {
             setTimeout(() => {
               if (!requestContext.response.http.body) {...

© BuildWithClaude Community · MIT · davepoon/buildwithclaude

Similar slash commands

All slash commands for Backend and APIs →

implement-graphql-api by other authors comes first.

implement-graphql-api davila7 implement-graphql-api — a slash command that builds a GraphQL API: schema, resolvers, subscriptions and N+1 protection. Useful when you need a real backend, not a sketch. CX Codex +1 212installs graphql-schema-designer patricio0312rev graphql-schema-designer is a Claude Code skill for shaping GraphQL APIs with types, queries, mutations, subscriptions, and resolvers. It activates for requests about schema design, GraphQL setup, or Apollo Server. CX Codex +1 230installs graphql-expert personamanagmentlayer graphql-expert is a Claude Code skill for GraphQL schema design, resolvers, and subscriptions, with guidance on Apollo federation and N+1 queries. CX Codex +1 169installs graphql-api-development manutej graphql-api-development — a skill for Claude Code, Codex, Cursor, Copilot and Gemini CLI covering GraphQL API construction: schema design, type system, resolvers, mutations, subscriptions, auth and caching. CX Codex +1 449installs graphql-development Mindrally graphql-development — a skill that gives the agent GraphQL guidelines: schema design, type-safe clients, React and Next.js integration. Useful when it writes resolvers and queries. CX Codex +1 701installs apollo-graphql sanjeed5 Enforces Apollo GraphQL conventions on both server and client. It kicks in for JavaScript and JSX files where the GraphQL schema must stay strict and documented. CX Codex +1 ★ 3,589repo stars graphql-schema apollographql graphql-schema guides GraphQL SDL schema design following Apollo best practices. Useful when creating schema.graphql, adding mutations, or setting up pagination. CX Codex +1 4,500installs

From the same set235

The whole set →
gsd-plan-checker gsd-plan-checker is a Claude Code subagent that checks whether phase plans can reach their goal before work begins. It flags missing requirements, broken dependencies, and incomplete tasks. CX Codex ★ 3,785repo stars gsd-doc-writer gsd-doc-writer — a subagent that writes and updates project documentation. Generates README, guides, API references, and other files, adapting to project structure and fixing errors from verification checks. CX Codex ★ 3,785repo stars design-rest-api design-rest-api guides your AI coding agent to plan and scaffold RESTful API architecture with Express.js routing, controller separation, and Joi validation. CX Codex +1 ★ 3,785repo stars create-database-migrations create-database-migrations is a Claude Code command for planning and managing database migrations. Run it to assess schema changes, rollback steps, and data safety. CX Codex +1 ★ 3,785repo stars gsd-debugger gsd-debugger investigates bugs using falsifiable hypotheses, manages persistent debug sessions, and handles checkpoints when manual input is needed. CX Codex ★ 3,785repo stars gsd-planner The gsd-planner subagent turns a development phase into executable plans, maps dependencies, and checks work backward from the goal. Run it through /gsd:plan-phase. CX Codex ★ 3,785repo stars production-fast-api-template production-fast-api-template is a Claude Code skill that defines conventions and file layout for a unified production-ready FastAPI backend with RAG and agentic AI on AWS ECS Fargate. CX Codex +1 ★ 3,785repo stars fix fix fetches vulnerability intelligence and suggests actionable package remediation steps for your project. CX Codex +1 ★ 3,785repo stars

Project sponsors

Companies that keep this analytics open