Skip to content
writing-graphql-operations logo

GraphQL Operations Developer

writing-graphql-operations

Creates GraphQL queries and mutations using gql.tada and urql. Implements repository pattern with type-safe operations and error handling. Triggers on: GraphQL query, GraphQL mutation, gql.tada, urql client, Saleor API, fragments, repository pattern, fetch-schema, MSW mocks.

mattnigh/skills_collection0installs24stars

SKILL.md

Full skill instructions

GraphQL Operations Developer

Purpose

Guide the creation and maintenance of GraphQL operations following project conventions for type safety, organization, error handling, and testing.

When to Use

  • Creating new GraphQL queries or mutations
  • Integrating with Saleor API endpoints
  • Updating schema after Saleor changes
  • Working with urql client configuration
  • Creating mocks for testing

Table of Contents

Project GraphQL Stack

ToolPurpose
urqlGraphQL client with caching
gql.tadaType-safe GraphQL with TypeScript inference
@urql/​exchange-authAuthentication handling
@urql/​exchange-retryRate limiting and retry logic

File Organization

src/​lib/​graphql/
├── client.ts              # urql client configuration
├── operations/            # GraphQL operation definitions
│   ├── products.ts
│   ├── categories.ts
│   └── ...
├── fragments/             # Reusable GraphQL fragments
│   └── ...
├── __mocks__/            # Test mocks
│   └── ...
└── schema.graphql        # Saleor schema (generated)

src/​modules/<entity>/
├── repository.ts          # Uses GraphQL operations
└── ...

Creating Operations with gql.tada

Basic Query

import { graphql } from 'gql.tada';

// gql.tada infers types from schema automatically
export const GetCategoriesQuery = graphql(`
  query GetCategories($first: Int!) {
    categories(first: $first) {
      edges {
        node {
          id
          name
          slug
          description
          parent {
            id
            slug
          }
        }
      }
    }
  }
`);

// Type is inferred automatically
type GetCategoriesResult = ResultOf<typeof GetCategoriesQuery>;

Query with Variables

export const GetCategoryBySlugQuery = graphql(`
  query GetCategoryBySlug($slug: String!) {
    category(slug: $slug) {
      id
      name
      slug
      description
      level
      parent {
        id
        slug
      }
      children(first: 100) {
        edges {
          node {
            id
            name
            slug
          }
        }
      }
    }
  }
`);

Mutation

export const CreateCategoryMutation = graphql(`
  mutation CreateCategory($input: CategoryInput!) {
    categoryCreate(input: $input) {
      category {
        id
        name
        slug
      }
      errors {
        field
        message
        code
      }
    }
  }
`);

Using Fragments

// Define reusable fragment
export const CategoryFieldsFragment = graphql(`
  fragment CategoryFields on Category {
    id
    name
    slug
    description
    level
  }
`);

// Use in query
export const GetCategoriesWithFragmentQuery = graphql(`
  query GetCategoriesWithFragment($first: Int!) {
    categories(first: $first) {
      edges {
        node {
          ...CategoryFields
        }
      }
    }
  }
`, [CategoryFieldsFragment]);

Repository Pattern

Standard Repository Structure

// src/​modules/​category/​repository.ts
import { Client } from '@urql/​core';
import { graphql } from 'gql.tada';
import { GraphQLError } from '@/​lib/​errors';

const GetCategoriesQuery = graphql(`...`);
const CreateCategoryMutation = graphql(`...`);

export class CategoryRepository {
  constructor(private readonly client: Client) {}

  async findAll(): Promise<Category[]> {
    const result = await this.client.query(GetCategoriesQuery, { first: 100 });

    if (result.error) {
      throw GraphQLError.fromCombinedError(result.error, 'GetCategories');
    }

    return this.mapCategories(result.data?.categories);
  }

  async create(input: CategoryInput): Promise<Category> {
    const result = await this.client.mutation(CreateCategoryMutation, { input });

    if (result.error) {
      throw GraphQLError.fromCombinedError(result.error, 'CreateCategory');
    }

    if (result.data?.categoryCreate?.errors?.length) {
      throw new GraphQLError(
        'Category creation failed',
        result.data.categoryCreate.errors
      );
    }

    return this.mapCategory(result.data?.categoryCreate?.category);
  }

  // Map GraphQL response to domain model
  private mapCategory(gqlCategory: GqlCategory | null): Category {
    if (!gqlCategory) {
      throw new EntityNotFoundError('Category not found');
    }
    return {
      id: gqlCategory.id,
      name: gqlCategory.name,
      slug: gqlCategory.slug,
      description: gqlCategory.description ?? undefined,
    };
  }
}

Error Handling

Wrapping GraphQL Errors

import { CombinedError } from '@urql/​core';
import { GraphQLError } from '@/​lib/​errors';

// In repository methods
if (result.error) {
  throw GraphQLError.fromCombinedError(
    result.error,
    'OperationName',
    { entitySlug: input.slug }  // Additional context
  );
}

// Handle mutation-specific errors
if (result.data?.mutationName?.errors?.length) {
  const errors = result.data.mutationName.errors;
  throw new GraphQLError(
    `Operation failed: ${errors.map(e => e.message).join(', ')}`,
    errors
  );
}

Common Error Scenarios

Error TypeCauseHandling
CombinedErrorNetwork/​GraphQL errorsGraphQLError.fromCombinedError()
errors arrayMutation validation errorsCheck result.data?.mutation?.errors
Rate limit (429)Too many requestsAutomatic retry via exchange
Auth errorInvalid/​expired tokenRe-authenticate

Schema Management

Updating Schema

# Fetch latest schema from Saleor instance
pnpm fetch-schema

# This updates:
# - src/​lib/​graphql/​schema.graphql
# - graphql-env.d.ts (type definitions)

When to Update Schema

  • New Saleor features needed
  • After Saleor version upgrade
  • When encountering schema drift errors
  • Commit schema changes with feature implementation

Testing GraphQL Operations

Mock Setup with MSW

// src/​lib/​graphql/​__mocks__/​category-mocks.ts
import { graphql, HttpResponse } from 'msw';

export const categoryHandlers = [
  graphql.query('GetCategories', () => {
    return HttpResponse.json({
      data: {
        categories: {
          edges: [
            {
              node: {
                id: 'cat-1',
                name: 'Electronics',
                slug: 'electronics',
              },
            },
          ],
        },
      },
    });
  }),

  graphql.mutation('CreateCategory', ({ variables }) => {
    return HttpResponse.json({
      data: {
        categoryCreate: {
          category: {
            id: 'new-cat',
            name: variables.input.name,
            slug: variables.input.slug,
          },
          errors: [],
        },
      },
    });
  }),
];

Repository Test Pattern

describe('CategoryRepository', () => {
  const server = setupServer(...categoryHandlers);

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  it('should fetch all categories', async () => {
    const repository = new CategoryRepository(testClient);
    const categories = await repository.findAll();

    expect(categories).toHaveLength(1);
    expect(categories[0].slug).toBe('electronics');
  });
});

Client Configuration

urql Client Setup

// src/​lib/​graphql/​client.ts
import { Client, cacheExchange, fetchExchange } from '@urql/​core';
import { authExchange } from '@urql/​exchange-auth';
import { retryExchange } from '@urql/​exchange-retry';

export const createClient = (url: string, token: string) => {
  return new Client({
    url,
    exchanges: [
      cacheExchange,
      authExchange(async utils => ({
        addAuthToOperation(operation) {
          return utils.appendHeaders(operation, {
            Authorization: `Bearer ${token}`,
          });
        },
      })),
      retryExchange({
        initialDelayMs: 1000,
        maxDelayMs: 15000,
        maxNumberAttempts: 5,
        retryIf: error => {
          // Retry on rate limits and network errors
          return error?.response?.status === 429 || !error?.response;
        },
      }),
      fetchExchange,
    ],
  });
};

Best Practices

Do's

  • Use gql.tada for all operations (type inference)
  • Keep operations close to their domain modules
  • Map GraphQL responses to domain models
  • Include operation name in error context
  • Update mocks when schema changes

Don'ts

  • Don't use raw string queries (no type safety)
  • Don't expose GraphQL types directly to services
  • Don't skip error handling for any operation
  • Don't hardcode pagination limits (use constants)

Validation Checkpoints

PhaseValidateCommand
Schema freshNo driftpnpm fetch-schema
Operations typedgql.tada inferenceCheck IDE types
Mocks matchMSW handlerspnpm test
Error handlingAll paths coveredCode review

Common Mistakes

MistakeIssueFix
Not checking errors arraySilent failuresAlways check result.data?.mutation?.errors
Exposing GraphQL typesCouplingMap to domain types in repository
Missing error contextHard to debugInclude operation name in errors
Stale schemaType errorsRun pnpm fetch-schema after Saleor updates
Not using fragmentsCode duplicationExtract shared fields to fragments

External Documentation

For up-to-date library docs, use Context7 MCP:

  • urql: mcp__context7__get-library-docs with /​urql-graphql/​urql
  • gql.tada: Use mcp__context7__resolve-library-id with "gql.tada"

References

Skill Reference Files

Project Resources

  • {baseDir}/​src/​lib/​graphql/​client.ts - Client configuration
  • {baseDir}/​src/​lib/​graphql/​operations/ - Existing operations
  • {baseDir}/​docs/​CODE_QUALITY.md#graphql--external-integrations - Quality standards

Related Skills

  • Complete entity workflow: See adding-entity-types for full implementation including bulk mutations
  • Bulk operations: See adding-entity-types/​references/​bulk-mutations.md for chunking patterns
  • Testing GraphQL: See analyzing-test-coverage for MSW setup

More skills from mattnigh

spring-framework-patterns logo
mattnigh/skills_collection

spring-framework-patterns

Comprehensive Spring Framework and Spring Boot best practices including dependency injection patterns, bean lifecycle and scopes, REST API development, Spring Data JPA, service layer design, Spring Security, testing strategies, caching, AOP, async processing, error handling, and common anti-patte...

24 0
View

TypeScript厳格モードによる型安全性設計を専門とするスキル。 📖 参照書籍: - 『Effective TypeScript』(Dan Vanderkam): 型設計 📚 リソース参照: - `resources/Level1_basics.md`: レベル1の基礎ガイド - `resources/Level2_intermediate.md`: レベル2の実務ガイド - `resources/Level3_advanced.md`: レベル3の応用ガイド - `resources/Level4_expert.md`: レベル4の専門ガイド - `resources/di...

24 0
View
deploying-cloud-k8s logo
mattnigh/skills_collection

deploying-cloud-k8s

Deploys applications to cloud Kubernetes (AKS/GKE/DOKS) with CI/CD pipelines. Use when deploying to production, setting up GitHub Actions, troubleshooting deployments. Covers build-time vs runtime vars, architecture matching, and battle-tested debugging.

24 0
View
moai-alfred-agent-guide logo
mattnigh/skills_collection

moai-alfred-agent-guide

19-agent team structure, decision trees for agent selection, Haiku vs Sonnet model selection, and agent collaboration principles. Use when deciding which sub-agent to invoke, understanding team responsibilities, or learning multi-agent orchestration.

24 0
View
mermaid-diagram-generator logo
mattnigh/skills_collection

mermaid-diagram-generator

Converts architecture descriptions, module specs, or workflow docs into Mermaid diagrams. Use when visualizing brick module relationships, workflows (DDD, investigation), or system architecture. Supports: flowcharts, sequence diagrams, class diagrams, state machines, entity relationship diagrams,...

24 0
View
pre-flight-check logo
mattnigh/skills_collection

pre-flight-check

INVOKE FIRST before any code work. Validates git workflow (branch, issue, worklog) and checks approach. Use at START of every task and END before completing. Prevents skipped steps.

24 0
View
browser-dev-tools logo
mattnigh/skills_collection

browser-dev-tools

This skill should be used when working with browser-rendered artifacts (i.e. Bun, React/React Native) to proactively validate that development work on localhost is being built appropriately and to support debugging browser-rendered content. Use this skill after making frontend changes to verify t...

24 0
View
lead-dev logo
mattnigh/skills_collection

lead-dev

Lead Développeur - Coordination technique opérationnelle, code review, mentoring et livraison. Pair de web-dev-process au niveau OPÉRATIONS.

24 0
View
worker-monitor logo
mattnigh/skills_collection

worker-monitor

Monitor Docker workers, RQ queue health, and auto-scale workers (max 4). Use when: checking job progress, monitoring queue depth, scaling workers up/down, diagnosing slow processing, or waiting for jobs to complete. Referenced by data-quality skill during reprocessing.

24 0
View
quality-advisor logo
mattnigh/skills_collection

quality-advisor

Proactive quality guidance system that monitors artifact creation and provides real-time feedback on documentation quality

24 0
View
bump-version logo
mattnigh/skills_collection

bump-version

This skill should be used when the user wants to bump the version number in the workspace. It updates versions across all pyproject.toml files (root, tde, and tda packages) and the CHANGELOG.md to keep them synchronized.

24 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View