名称: GraphQL 移动端 描述: 为移动应用程序提供 GraphQL 客户端集成功能 版本: 1.0.0 类别: API 集成 标识符: graphql-mobile 状态: 活跃
GraphQL 移动端技能
概述
此技能为移动应用程序提供 GraphQL 客户端集成能力。它支持配置 Apollo Client、代码生成、缓存策略和实时订阅。
允许使用的工具
bash- 执行代码生成和构建工具read- 分析 GraphQL 模式和查询write- 生成类型化操作和配置edit- 更新 GraphQL 实现glob- 搜索 GraphQL 文件grep- 搜索模式
能力
Apollo Client (React Native)
-
客户端配置
- 配置 Apollo Client
- 设置 HTTP 和 WebSocket 链接
- 配置身份验证
- 处理错误策略
-
缓存
- 配置 InMemoryCache
- 实现类型策略
- 处理缓存规范化
- 配置持久化
代码生成
- GraphQL 代码生成
- 生成 TypeScript 类型
- 生成 React hooks
- 生成片段
- 处理自定义标量
Flutter GraphQL
- graphql_flutter
- 配置 GraphQL 客户端
- 实现查询和变更
- 处理订阅
- 配置缓存
原生客户端
-
Apollo iOS
- 配置 Apollo iOS 客户端
- 生成 Swift 类型
- 处理缓存
- 实现订阅
-
Apollo Android
- 配置 Apollo Kotlin 客户端
- 生成 Kotlin 类型
- 处理规范化缓存
实时功能
- 订阅
- 配置 WebSocket 链接
- 处理重新连接
- 实现订阅钩子
- 管理活动订阅
目标流程
graphql-apollo-integration.js- GraphQL 实现offline-first-architecture.js- 离线缓存mobile-performance-optimization.js- 查询优化
依赖项
- Apollo Client
- GraphQL Codegen
- 平台特定的 GraphQL 库
使用示例
Apollo Client 设置 (React Native)
// apollo/client.ts
import { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { setContext } from '@apollo/client/link/context';
import { createClient } from 'graphql-ws';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AsyncStorageWrapper, CachePersistor } from 'apollo3-cache-persist';
const httpLink = createHttpLink({
uri: 'https://api.example.com/graphql',
});
const wsLink = new GraphQLWsLink(
createClient({
url: 'wss://api.example.com/graphql',
connectionParams: async () => {
const token = await AsyncStorage.getItem('authToken');
return { authorization: token ? `Bearer ${token}` : '' };
},
})
);
const authLink = setContext(async (_, { headers }) => {
const token = await AsyncStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
wsLink,
authLink.concat(httpLink)
);
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
keyArgs: false,
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
});
export const persistor = new CachePersistor({
cache,
storage: new AsyncStorageWrapper(AsyncStorage),
});
export const client = new ApolloClient({
link: splitLink,
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
},
});
GraphQL 代码生成配置
# codegen.yml
schema: https://api.example.com/graphql
documents: 'src/**/*.graphql'
generates:
src/generated/graphql.ts:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
config:
withHooks: true
withComponent: false
withHOC: false
skipTypename: false
dedupeFragments: true
查询钩子用法
// features/posts/hooks/usePosts.ts
import { usePostsQuery, useCreatePostMutation } from '../../../generated/graphql';
export function usePosts() {
const { data, loading, error, refetch, fetchMore } = usePostsQuery({
variables: { first: 10 },
notifyOnNetworkStatusChange: true,
});
const [createPost] = useCreatePostMutation({
update(cache, { data }) {
cache.modify({
fields: {
posts(existingPosts = []) {
const newPostRef = cache.writeFragment({
data: data?.createPost,
fragment: PostFragmentDoc,
});
return [newPostRef, ...existingPosts];
},
},
});
},
optimisticResponse: (variables) => ({
__typename: 'Mutation',
createPost: {
__typename: 'Post',
id: 'temp-id',
title: variables.title,
body: variables.body,
createdAt: new Date().toISOString(),
},
}),
});
const loadMore = () => {
if (data?.posts.pageInfo.hasNextPage) {
fetchMore({
variables: {
after: data.posts.pageInfo.endCursor,
},
});
}
};
return {
posts: data?.posts.edges.map((e) => e.node) ?? [],
loading,
error,
refetch,
loadMore,
createPost,
};
}
Apollo iOS 设置
// Apollo/Network.swift
import Apollo
import ApolloWebSocket
class Network {
static let shared = Network()
private(set) lazy var apollo: ApolloClient = {
let store = ApolloStore(cache: InMemoryNormalizedCache())
let provider = DefaultInterceptorProvider(store: store)
let url = URL(string: "https://api.example.com/graphql")!
let transport = RequestChainNetworkTransport(
interceptorProvider: provider,
endpointURL: url
)
return ApolloClient(networkTransport: transport, store: store)
}()
}
质量门限
- 通过代码生成确保类型安全
- 查询复杂度限制
- 缓存一致性已验证
- 订阅重新连接已测试
相关技能
rest-api-integration- REST 集成offline-storage- 离线缓存firebase-mobile- Firebase 替代方案
版本历史
- 1.0.0 - 初始版本