Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问clear审计提醒

apollo-client-patterns阿波罗客户端模式

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

441

周安装

18

GitHub Stars

142

下载量

141
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:apollo-client-patterns(阿波罗客户端模式)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/apollo-client-patterns
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill apollo-client-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill apollo-client-patterns

简介

apollo-client-patterns 用于辅助前端页面、组件、样式和交互逻辑的开发与维护,适合生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码。

  • 它能帮助整理组件结构、定位布局和性能问题,适用于前端项目的代码生成与审查。
  • 使用时需结合项目现有设计系统、路由和构建方式,避免生成孤立片段;涉及页面改动时应配合本地预览和构建检查。
  • 安装前建议确认权限范围和维护状态,注意是否触发文件读写或网络请求。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Apollo Client Patterns

Master Apollo Client for building efficient GraphQL applications with proper query management, caching strategies, and state handling.

Overview

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It integrates seamlessly with React and provides powerful caching mechanisms.

Installation and Setup

Installing Apollo Client

# Install Apollo Client and dependencies
npm install @apollo/client graphql

# For React applications
npm install @apollo/client graphql react

# Additional packages
npm install graphql-tag @apollo/client/link/error

Basic Configuration

// src/apollo/client.js
import {
  ApolloClient,
  InMemoryCache,
  createHttpLink,
  from
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';

const httpLink = createHttpLink({
  uri: process.env.REACT_APP_GRAPHQL_URI || 'http://localhost:4000/graphql',
});

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

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) =>
      console.error(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );
  }
  if (networkError) {
    console.error(`[Network error]: ${networkError}`);
  }
});

const client = new ApolloClient({
  link: from([errorLink, authLink, httpLink]),
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          posts: {
            merge(existing, incoming) {
              return incoming;
            }
          }
        }
      }
    }
  }),
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
      errorPolicy: 'all',
    },
    query: {
      fetchPolicy: 'network-only',
      errorPolicy: 'all',
    },
  },
});

export default client;

Provider Setup

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apollo/client';
import App from './App';

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
);

Core Patterns

1. Basic Queries

// src/graphql/queries.js
import { gql } from '@apollo/client';

export const GET_POSTS = gql`
  query GetPosts($limit: Int, $offset: Int) {
    posts(limit: $limit, offset: $offset) {
      id
      title
      body
      author {
        id
        name
        avatar
      }
      createdAt
    }
  }
`;

export const GET_POST = gql`
  query GetPost($id: ID!) {
    post(id: $id) {
      id
      title
      body
      author {
        id
        name
      }
      comments {
        id
        body
        author {
          id
          name
        }
      }
    }
  }
`;

// src/components/PostsList.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../graphql/queries';

function PostsList() {
  const { loading, error, data, refetch, fetchMore } = useQuery(GET_POSTS, {
    variables: { limit: 10, offset: 0 },
    notifyOnNetworkStatusChange: true,
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <button onClick={() => refetch()}>Refresh</button>

      {data.posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
          <span>By {post.author.name}</span>
        </article>
      ))}

      <button
        onClick={() =>
          fetchMore({
            variables: { offset: data.posts.length },
            updateQuery: (prev, { fetchMoreResult }) => {
              if (!fetchMoreResult) return prev;
              return {
                posts: [...prev.posts, ...fetchMoreResult.posts]
              };
            }
          })
        }
      >
        Load More
      </button>
    </div>
  );
}

export default PostsList;

2. Mutations

// src/graphql/mutations.js
import { gql } from '@apollo/client';

export const CREATE_POST = gql`
  mutation CreatePost($input: CreatePostInput!) {
    createPost(input: $input) {
      id
      title
      body
      author {
        id
        name
      }
      createdAt
    }
  }
`;

export const UPDATE_POST = gql`
  mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
    updatePost(id: $id, input: $input) {
      id
      title
      body
    }
  }
`;

export const DELETE_POST = gql`
  mutation DeletePost($id: ID!) {
    deletePost(id: $id) {
      id
    }
  }
`;

// src/components/CreatePost.js
import React, { useState } from 'react';
import { useMutation } from '@apollo/client';
import { CREATE_POST } from '../graphql/mutations';
import { GET_POSTS } from '../graphql/queries';

function CreatePost() {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const [createPost, { loading, error }] = useMutation(CREATE_POST, {
    update(cache, { data: { createPost } }) {
      const { posts } = cache.readQuery({ query: GET_POSTS });
      cache.writeQuery({
        query: GET_POSTS,
        data: { posts: [createPost, ...posts] }
      });
    },
    onCompleted: () => {
      setTitle('');
      setBody('');
    },
    onError: (error) => {
      console.error('Error creating post:', error);
    }
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    createPost({
      variables: {
        input: { title, body }
      }
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={title}
        onChange={e => setTitle(e.target.value)}
        placeholder="Title"
        disabled={loading}
      />
      <textarea
        value={body}
        onChange={e => setBody(e.target.value)}
        placeholder="Body"
        disabled={loading}
      />
      <button type="submit" disabled={loading}>
        {loading ? 'Creating...' : 'Create Post'}
      </button>
      {error && <p>Error: {error.message}</p>}
    </form>
  );
}

export default CreatePost;

3. Cache Management

// src/apollo/cache.js
import { InMemoryCache, makeVar } from '@apollo/client';

// Reactive variables
export const cartItemsVar = makeVar([]);
export const isLoggedInVar = makeVar(!!localStorage.getItem('authToken'));

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        cartItems: {
          read() {
            return cartItemsVar();
          }
        },
        isLoggedIn: {
          read() {
            return isLoggedInVar();
          }
        },
        // Pagination with field policies
        posts: {
          keyArgs: false,
          merge(existing = [], incoming, { args }) {
            const merged = existing ? existing.slice(0) : [];
            const offset = args?.offset || 0;

            for (let i = 0; i < incoming.length; i++) {
              merged[offset + i] = incoming[i];
            }

            return merged;
          }
        }
      }
    },
    Post: {
      fields: {
        // Computed field
        isLiked: {
          read(_, { readField }) {
            const likes = readField('likes');
            const currentUserId = localStorage.getItem('userId');
            return likes?.some(like => like.userId === currentUserId);
          }
        }
      }
    }
  }
});

// Cache manipulation helpers
export function addToCart(item) {
  const currentCart = cartItemsVar();
  cartItemsVar([...currentCart, item]);
}

export function removeFromCart(itemId) {
  const currentCart = cartItemsVar();
  cartItemsVar(currentCart.filter(item => item.id !== itemId));
}

// Manual cache updates
export function updatePostInCache(client, postId, updates) {
  const post = client.readFragment({
    id: `Post:${postId}`,
    fragment: gql`
      fragment PostUpdate on Post {
        id
        title
        body
      }
    `
  });

  if (post) {
    client.writeFragment({
      id: `Post:${postId}`,
      fragment: gql`
        fragment PostUpdate on Post {
          id
          title
          body
        }
      `,
      data: {
        ...post,
        ...updates
      }
    });
  }
}

4. Optimistic Updates

// src/components/LikeButton.js
import React from 'react';
import { useMutation } from '@apollo/client';
import { gql } from '@apollo/client';

const LIKE_POST = gql`
  mutation LikePost($postId: ID!) {
    likePost(postId: $postId) {
      id
      likesCount
      isLiked
    }
  }
`;

function LikeButton({ post }) {
  const [likePost] = useMutation(LIKE_POST, {
    variables: { postId: post.id },
    optimisticResponse: {
      __typename: 'Mutation',
      likePost: {
        __typename: 'Post',
        id: post.id,
        likesCount: post.likesCount + 1,
        isLiked: true,
      }
    },
    update(cache, { data: { likePost } }) {
      cache.modify({
        id: cache.identify(post),
        fields: {
          likesCount() {
            return likePost.likesCount;
          },
          isLiked() {
            return likePost.isLiked;
          }
        }
      });
    }
  });

  return (
    <button onClick={() => likePost()}>
      {post.isLiked ? 'Unlike' : 'Like'} ({post.likesCount})
    </button>
  );
}

export default LikeButton;

5. Subscriptions

// src/graphql/subscriptions.js
import { gql } from '@apollo/client';

export const POST_CREATED = gql`
  subscription OnPostCreated {
    postCreated {
      id
      title
      body
      author {
        id
        name
      }
      createdAt
    }
  }
`;

// src/components/RealtimePosts.js
import React from 'react';
import { useQuery, useSubscription } from '@apollo/client';
import { GET_POSTS } from '../graphql/queries';
import { POST_CREATED } from '../graphql/subscriptions';

function RealtimePosts() {
  const { data, loading } = useQuery(GET_POSTS);

  useSubscription(POST_CREATED, {
    onSubscriptionData: ({ client, subscriptionData }) => {
      const newPost = subscriptionData.data.postCreated;

      client.cache.modify({
        fields: {
          posts(existingPosts = []) {
            const newPostRef = client.cache.writeFragment({
              data: newPost,
              fragment: gql`
                fragment NewPost on Post {
                  id
                  title
                  body
                  author {
                    id
                    name
                  }
                }
              `
            });
            return [newPostRef, ...existingPosts];
          }
        }
      });
    }
  });

  if (loading) return <p>Loading...</p>;

  return (
    <div>
      {data.posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </article>
      ))}
    </div>
  );
}

export default RealtimePosts;

6. Lazy Queries

// src/components/SearchPosts.js
import React, { useState } from 'react';
import { useLazyQuery } from '@apollo/client';
import { gql } from '@apollo/client';

const SEARCH_POSTS = gql`
  query SearchPosts($query: String!) {
    searchPosts(query: $query) {
      id
      title
      excerpt
    }
  }
`;

function SearchPosts() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchPosts, { loading, data, error, called }] = useLazyQuery(
    SEARCH_POSTS,
    {
      fetchPolicy: 'network-only'
    }
  );

  const handleSearch = (e) => {
    e.preventDefault();
    if (searchTerm.trim()) {
      searchPosts({ variables: { query: searchTerm } });
    }
  };

  return (
    <div>
      <form onSubmit={handleSearch}>
        <input
          value={searchTerm}
          onChange={e => setSearchTerm(e.target.value)}
          placeholder="Search posts..."
        />
        <button type="submit">Search</button>
      </form>

      {loading && <p>Searching...</p>}
      {error && <p>Error: {error.message}</p>}

      {called && data && (
        <ul>
          {data.searchPosts.map(post => (
            <li key={post.id}>
              <h3>{post.title}</h3>
              <p>{post.excerpt}</p>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default SearchPosts;

7. Error Handling

// src/components/PostWithErrorHandling.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POST } from '../graphql/queries';

function PostWithErrorHandling({ postId }) {
  const { loading, error, data } = useQuery(GET_POST, {
    variables: { id: postId },
    errorPolicy: 'all', // Return partial data and errors
    onError: (error) => {
      // Custom error handling
      if (error.networkError) {
        console.error('Network error:', error.networkError);
      }
      if (error.graphQLErrors) {
        error.graphQLErrors.forEach(({ message, extensions }) => {
          if (extensions.code === 'UNAUTHENTICATED') {
            // Redirect to login
            window.location.href = '/login';
          }
        });
      }
    }
  });

  if (loading) return <p>Loading...</p>;

  if (error && !data) {
    return (
      <div className="error">
        <h3>Something went wrong</h3>
        <p>{error.message}</p>
        <button onClick={() => window.location.reload()}>
          Try Again
        </button>
      </div>
    );
  }

  // Partial data with errors
  if (error && data) {
    console.warn('Partial data with errors:', error);
  }

  return (
    <article>
      <h1>{data.post.title}</h1>
      <p>{data.post.body}</p>
    </article>
  );
}

export default PostWithErrorHandling;

8. Pagination Patterns

// src/components/PaginatedPosts.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { gql } from '@apollo/client';

const GET_PAGINATED_POSTS = gql`
  query GetPaginatedPosts($cursor: String, $limit: Int!) {
    posts(cursor: $cursor, limit: $limit) {
      edges {
        node {
          id
          title
          body
        }
        cursor
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
`;

function PaginatedPosts() {
  const { data, loading, fetchMore, networkStatus } = useQuery(
    GET_PAGINATED_POSTS,
    {
      variables: { limit: 10 },
      notifyOnNetworkStatusChange: true,
    }
  );

  const loadMore = () => {
    fetchMore({
      variables: {
        cursor: data.posts.pageInfo.endCursor
      }
    });
  };

  if (loading && networkStatus !== 3) return <p>Loading...</p>;

  return (
    <div>
      {data.posts.edges.map(({ node }) => (
        <article key={node.id}>
          <h2>{node.title}</h2>
          <p>{node.body}</p>
        </article>
      ))}

      {data.posts.pageInfo.hasNextPage && (
        <button onClick={loadMore} disabled={networkStatus === 3}>
          {networkStatus === 3 ? 'Loading...' : 'Load More'}
        </button>
      )}
    </div>
  );
}

export default PaginatedPosts;

9. Local State Management

// src/graphql/local.js
import { gql, makeVar } from '@apollo/client';

// Reactive variables
export const themeVar = makeVar('light');
export const sidebarOpenVar = makeVar(false);

// Local-only fields
export const LOCAL_STATE = gql`
  query GetLocalState {
    theme @client
    sidebarOpen @client
  }
`;

// Type policies for local state
export const localStateTypePolicies = {
  Query: {
    fields: {
      theme: {
        read() {
          return themeVar();
        }
      },
      sidebarOpen: {
        read() {
          return sidebarOpenVar();
        }
      }
    }
  }
};

// src/components/ThemeToggle.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { LOCAL_STATE, themeVar } from '../graphql/local';

function ThemeToggle() {
  const { data } = useQuery(LOCAL_STATE);

  const toggleTheme = () => {
    const newTheme = data.theme === 'light' ? 'dark' : 'light';
    themeVar(newTheme);
    localStorage.setItem('theme', newTheme);
  };

  return (
    <button onClick={toggleTheme}>
      Current theme: {data.theme}
    </button>
  );
}

export default ThemeToggle;

10. Custom Hooks

// src/hooks/usePosts.js
import { useQuery, useMutation } from '@apollo/client';
import { GET_POSTS, GET_POST } from '../graphql/queries';
import { CREATE_POST, UPDATE_POST, DELETE_POST } from '../graphql/mutations';

export function usePosts() {
  const { data, loading, error, refetch } = useQuery(GET_POSTS);

  return {
    posts: data?.posts || [],
    loading,
    error,
    refetch
  };
}

export function usePost(id) {
  const { data, loading, error } = useQuery(GET_POST, {
    variables: { id },
    skip: !id
  });

  return {
    post: data?.post,
    loading,
    error
  };
}

export function useCreatePost() {
  const [createPost, { loading, error }] = useMutation(CREATE_POST, {
    update(cache, { data: { createPost } }) {
      cache.modify({
        fields: {
          posts(existingPosts = []) {
            const newPostRef = cache.writeFragment({
              data: createPost,
              fragment: gql`
                fragment NewPost on Post {
                  id
                  title
                  body
                }
              `
            });
            return [newPostRef, ...existingPosts];
          }
        }
      });
    }
  });

  return { createPost, loading, error };
}

// Usage
function MyComponent() {
  const { posts, loading } = usePosts();
  const { createPost } = useCreatePost();

  // ...
}

Best Practices

  1. Use fragments - Share field selections across queries
  2. Implement error boundaries - Gracefully handle errors
  3. Optimize cache configuration - Configure type policies properly
  4. Use optimistic updates - Improve perceived performance
  5. Implement proper loading states - Show feedback during operations
  6. Avoid over-fetching - Request only needed fields
  7. Leverage automatic cache - Let Apollo handle caching
  8. Use reactive variables - Manage local state efficiently
  9. Implement pagination - Handle large datasets properly
  10. Monitor network status - Track query states accurately

Common Pitfalls

  1. Cache inconsistencies - Not updating cache after mutations
  2. Over-fetching data - Requesting unnecessary fields
  3. Missing error handling - Not handling network/GraphQL errors
  4. Polling abuse - Excessive polling causing performance issues
  5. Not using fragments - Duplicating field selections
  6. Improper cache normalization - Missing or wrong cache IDs
  7. Memory leaks - Not cleaning up subscriptions
  8. Stale data - Using wrong fetch policies
  9. Missing loading states - Poor user experience
  10. Auth token issues - Not refreshing expired tokens

When to Use

  • Building React applications with GraphQL APIs
  • Managing complex application state
  • Implementing real-time features
  • Creating data-driven UIs
  • Building mobile apps with React Native
  • Developing admin dashboards
  • Creating collaborative applications
  • Implementing offline-first features
  • Building e-commerce platforms
  • Developing social media applications

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenCode

28.11%
按下载量换算40

Codex

25.32%
按下载量换算36

Claude Code

18.91%
按下载量换算27

windsurf

11.51%
按下载量换算16

Antigravity

8.41%
按下载量换算12

Gemini CLI

3.44%
按下载量换算5

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills