Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)48k · #4783

graphql-schema

Skill này làm gì

Công cụ này giúp tổ chức và viết code để giao tiếp với máy chủ dữ liệu bằng GraphQL. Nó đảm bảo các truy vấn và thay đổi dữ liệu được thực hiện đúng và hiệu quả.

Khi nào nên dùng

  • ✓Khi tạo các truy vấn GraphQL mới hoặc thay đổi dữ liệu.
  • ✓Khi làm việc với các thư viện như Apollo Client để quản lý dữ liệu.
  • ✓Khi tự động tạo các kiểu dữ liệu cho code của bạn.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/graphql-schema/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/graphql-schema/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm thế nào để viết truy vấn lấy tất cả người dùng và email của họ?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Bạn viết các truy vấn và mutation trong các tệp riêng có đuôi `.gql`. Sau đó, một chương trình đặc biệt sẽ tạo ra code cần thiết để dùng các định nghĩa này trong ứng dụng, đảm bảo mọi thứ hoạt động đúng.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

GraphQL Schema Patterns

When to Use

Use this skill when you need graphQL queries, mutations, and code generation patterns. Use when creating GraphQL operations, working with Apollo Client, or generating types.

Core Rules

  1. NEVER inline gql literals - Create .gql files
  2. ALWAYS run codegen after creating/modifying .gql files
  3. ALWAYS add onError handler to mutations
  4. Use generated hooks - Never write raw Apollo hooks

File Structure

src/
├── components/
│   └── ItemList/
│       ├── ItemList.tsx
│       ├── GetItems.gql           # Query definition
│       └── GetItems.generated.ts  # Auto-generated (don't edit)
└── graphql/
    └── mutations/
        └── CreateItem.gql         # Shared mutations

Creating a Query

Step 1: Create .gql file

# src/components/ItemList/GetItems.gql
query GetItems($limit: Int, $offset: Int) {
  items(limit: $limit, offset: $offset) {
    id
    name
    description
    createdAt
  }
}

Step 2: Run codegen

npm run gql:typegen

Step 3: Import and use generated hook

import { useGetItemsQuery } from './GetItems.generated';

const ItemList = () => {
  const { data, loading, error, refetch } = useGetItemsQuery({
    variables: { limit: 20, offset: 0 },
  });

  if (error) return <ErrorState error={error} onRetry={refetch} />;
  if (loading && !data) return <LoadingSkeleton />;
  if (!data?.items.length) return <EmptyState />;

  return <List items={data.items} />;
};

Creating a Mutation

Step 1: Create .gql file

# src/graphql/mutations/CreateItem.gql
mutation CreateItem($input: CreateItemInput!) {
  createItem(input: $input) {
    id
    name
    description
  }
}

Step 2: Run codegen

npm run gql:typegen

Step 3: Use with REQUIRED error handling

import { useCreateItemMutation } from 'graphql/mutations/CreateItem.generated';

const CreateItemForm = () => {
  const [createItem, { loading }] = useCreateItemMutation({
    // Success handling
    onCompleted: (data) => {
      toast.success({ title: 'Item created' });
      navigation.goBack();
    },
    // ERROR HANDLING IS REQUIRED
    onError: (error) => {
      console.error('createItem failed:', error);
      toast.error({ title: 'Failed to create item' });
    },
    // Cache update
    update: (cache, { data }) => {
      if (data?.createItem) {
        cache.modify({
          fields: {
            items: (existing = []) => [...existing, data.createItem],
          },
        });
      }
    },
  });

  return (
    <Button
      onPress={() => createItem({ variables: { input: formValues } })}
      isDisabled={!isValid || loading}
      isLoading={loading}
    >
      Create
    </Button>
  );
};

Mutation UI Requirements

CRITICAL: Every mutation trigger must:

  1. Be disabled during mutation - Prevent double-clicks
  2. Show loading state - Visual feedback
  3. Have onError handler - User knows it failed
  4. Show success feedback - User knows it worked
// CORRECT - Complete mutation pattern
const [submit, { loading }] = useSubmitMutation({
  onError: (error) => {
    console.error('submit failed:', error);
    toast.error({ title: 'Save failed' });
  },
  onCompleted: () => {
    toast.success({ title: 'Saved' });
  },
});

<Button
  onPress={handleSubmit}
  isDisabled={!isValid || loading}
  isLoading={loading}
>
  Submit
</Button>

Query Options

Fetch Policies

Policy Use When
cache-first Data rarely changes
cache-and-network Want fast + fresh (default)
network-only Always need latest
no-cache Never cache (rare)

Common Options

useGetItemsQuery({
  variables: { id: itemId },

  // Fetch strategy
  fetchPolicy: 'cache-and-network',

  // Re-render on network status changes
  notifyOnNetworkStatusChange: true,

  // Skip if condition not met
  skip: !itemId,

  // Poll for updates
  pollInterval: 30000,
});

Optimistic Updates

For instant UI feedback:

const [toggleFavorite] = useToggleFavoriteMutation({
  optimisticResponse: {
    toggleFavorite: {
      __typename: 'Item',
      id: itemId,
      isFavorite: !currentState,
    },
  },
  onError: (error) => {
    // Rollback happens automatically
    console.error('toggleFavorite failed:', error);
    toast.error({ title: 'Failed to update' });
  },
});

…

Câu hỏi thường gặp

“Query” và “mutation” là gì?

“Query” giống như câu hỏi bạn gửi đến máy chủ để lấy dữ liệu. “Mutation” giống như lệnh để thay đổi dữ liệu trên máy chủ (tạo, cập nhật hoặc xóa).

Tại sao tôi không nên viết code `gql` trực tiếp?

Viết trực tiếp dễ gây lỗi và khó bảo trì. Dùng tệp `.gql` và tự động tạo code giúp đảm bảo tính nhất quán và tránh sự cố.

“Codegen” là gì?

“Codegen” (tạo code) là quy trình tự động tạo một phần code dựa trên định nghĩa GraphQL. Điều này giúp tiết kiệm thời gian và giảm lỗi.

Chi tiết

Mô tả gốc của tác giả

GraphQL queries, mutations, and code generation patterns. Use when creating GraphQL operations, working with Apollo Client, or generating types.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#4783
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự