前端GraphQL客户端:优雅地获取数据

前端GraphQL客户端:优雅地获取数据

毒舌时刻

前端GraphQL?这不是后端的事吗?

"REST API就够了,为什么要用GraphQL"——结果前端需要多次请求,数据冗余,
"GraphQL太复杂了,我学不会"——结果错过了更灵活的数据获取方式,
"我直接用fetch请求GraphQL,多简单"——结果缺少缓存、错误处理等功能。

醒醒吧,GraphQL不是后端的专利,前端也需要专业的客户端工具!

为什么你需要这个?

  • 减少网络请求:一次请求获取所有需要的数据
  • 数据精确:只获取需要的数据,避免冗余
  • 类型安全:自动生成TypeScript类型
  • 缓存优化:智能缓存,减少重复请求
  • 开发效率:简化数据获取逻辑

反面教材

// 反面教材:直接使用fetch请求GraphQL async function fetchGraphQL(query, variables) { const response = await fetch('https://api.example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query, variables }), }); const data = await response.json(); if (data.errors) { console.error('GraphQL errors:', data.errors); throw new Error('GraphQL request failed'); } return data.data; } // 反面教材:重复请求相同数据 async function loadUserAndPosts() { // 第一次请求用户信息 const { user } = await fetchGraphQL(` query GetUser($id: ID!) { user(id: $id) { id name email } } `, { id: 1 }); // 第二次请求用户的帖子 const { user: userWithPosts } = await fetchGraphQL(` query GetUserWithPosts($id: ID!) { user(id: $id) { id posts { id title content } } } `, { id: 1 }); return { user, posts: userWithPosts.posts }; } 

正确的做法

// 正确的做法:使用Apollo Client import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; // 创建Apollo Client实例 const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache: new InMemoryCache(), headers: { authorization: localStorage.getItem('token') || '' } }); // 定义查询 const GET_USER_WITH_POSTS = gql` query GetUserWithPosts($id: ID!) { user(id: $id) { id name email posts { id title content createdAt } } } `; // 定义变更 const CREATE_POST = gql` mutation CreatePost($input: PostInput!) { createPost(input: $input) { id title content createdAt } } `; // 在React组件中使用 import React from 'react'; import { useQuery, useMutation } from '@apollo/client'; function UserProfile({ userId }) { // 使用useQuery钩子获取数据 const { loading, error, data, refetch } = useQuery(GET_USER_WITH_POSTS, { variables: { id: userId }, // 缓存策略 fetchPolicy: 'cache-and-network' }); // 使用useMutation钩子执行变更 const [createPost, { loading: creating }] = useMutation(CREATE_POST, { // 变更后更新缓存 update(cache, { data: { createPost } }) { const { user } = cache.readQuery({ query: GET_USER_WITH_POSTS, variables: { id: userId } }); cache.writeQuery({ query: GET_USER_WITH_POSTS, variables: { id: userId }, data: { user: { ...user, posts: [...user.posts, createPost] } } }); } }); if (loading) return <div>加载中...</div>; if (error) return <div>错误:{error.message}</div>; const handleCreatePost = async (title, content) => { await createPost({ variables: { input: { title, content, userId } } }); }; return ( <div> <h2>{data.user.name}</h2> <p>{data.user.email}</p> <h3>帖子</h3> <ul> {data.user.posts.map(post => ( <li key={post.id}> <h4>{post.title}</h4> <p>{post.content}</p> <p>{post.createdAt}</p> </li> ))} </ul> <button onClick={() => refetch()}>刷新</button> <button onClick={() => handleCreatePost('新帖子', '帖子内容')} disabled={creating} > {creating ? '创建中...' : '创建帖子'} </button> </div> ); } // 正确的做法:使用URQL import { createClient, gql } from 'urql'; // 创建URQL客户端 const client = createClient({ url: 'https://api.example.com/graphql', fetchOptions: () => ({ headers: { authorization: localStorage.getItem('token') || '' } }) }); // 在React组件中使用 import React from 'react'; import { useQuery, useMutation } from 'urql'; function UserList() { const [result, reexecuteQuery] = useQuery({ query: gql` query GetUsers { users { id name email } } ` }); const { data, fetching, error } = result; if (fetching) return <div>加载中...</div>; if (error) return <div>错误:{error.message}</div>; return ( <div> <h2>用户列表</h2> <ul> {data.users.map(user => ( <li key={user.id}> {user.name} - {user.email} </li> ))} </ul> <button onClick={() => reexecuteQuery()}>刷新</button> </div> ); } // 正确的做法:使用Relay import { Environment, Network, RecordSource, Store, useLazyLoadQuery, graphql } from 'relay-runtime'; // 创建Relay环境 function fetchQuery(operation, variables) { return fetch('https://api.example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', authorization: localStorage.getItem('token') || '' }, body: JSON.stringify({ query: operation.text, variables, }), }).then(response => { return response.json(); }); } const environment = new Environment({ network: Network.create(fetchQuery), store: new Store(new RecordSource()), }); // 定义查询 const UserQuery = graphql` query UserQuery($id: ID!) { user(id: $id) { id name email posts { edges { node { id title content } } } } } `; // 在React组件中使用 function UserDetail({ userId }) { const data = useLazyLoadQuery( UserQuery, { id: userId } ); return ( <div> <h2>{data.user.name}</h2> <p>{data.user.email}</p> <h3>帖子</h3> <ul> {data.user.posts.edges.map(edge => ( <li key={edge.node.id}> <h4>{edge.node.title}</h4> <p>{edge.node.content}</p> </li> ))} </ul> </div> ); } 

毒舌点评

看看,这才叫前端GraphQL客户端!不是简单地使用fetch请求,而是使用Apollo Client、URQL或Relay等专业的客户端工具。

记住,GraphQL客户端不仅仅是发送请求,还包括缓存管理、错误处理、类型生成等功能。这些工具可以大大简化你的前端代码,提高开发效率。

所以,别再觉得GraphQL复杂了,使用专业的客户端工具,让数据获取变得更加优雅!

总结

  • Apollo Client:功能强大,生态丰富,适合大型应用
  • URQL:轻量级,API简洁,适合中小型应用
  • Relay:Facebook开发,性能优异,适合大型应用
  • 缓存管理:智能缓存,减少重复请求
  • 类型安全:自动生成TypeScript类型
  • 错误处理:统一的错误处理机制
  • 变更管理:执行GraphQL变更并更新缓存
  • 开发工具:GraphQL Playground、Apollo DevTools等

前端GraphQL客户端,让数据获取变得更加优雅!

Read more

MCAP :机器人数据容器的全面实践指南

Outline: MCAP 已形成完整工具链生态: * Foxglove Studio:可视化分析工具 * mcap-cli:跨平台命令行工具 * AWS RoboMaker:原生云存储支持 随着 IEEE 正在制定的 P3196 机器人数据标准,MCAP 正在演进为行业基础架构的重要组成。其设计哲学启示我们:优秀的数据格式应该在存储效率与读取便利间找到平衡,这正是 MCAP 在机器人革命中脱颖而出的关键。 参考资料: 1. https://juejin.cn/post/7508575831791812658 https://getiot.tech/fileformat/mcap/ MCAP :机器人数据容器的全面实践指南 在机器人和自动驾驶系统开发中,高效存储和处理传感器数据是核心挑战之一。传统的 ROS bag 格式在面对大规模、多类型数据时逐渐暴露出性能瓶颈,而 MCAP(Modular Container for Asynchronous

Moon VR Video Player中文版下载地址及使用教程:支持8K/12K+多音轨外挂字幕 Moon VR Video Player中文版、Moon VR播放器下载、VR视频播放器推荐、Ste

Moon VR Video Player中文版下载地址及使用教程:支持8K/12K+多音轨外挂字幕 Moon VR Video Player中文版、Moon VR播放器下载、VR视频播放器推荐、Ste

Moon VR Video Player中文版下载地址及使用教程:支持8K/12K+多音轨外挂字幕 关键词:Moon VR Video Player中文版、Moon VR播放器下载、VR视频播放器推荐、SteamVR播放器、多音轨外挂字幕播放器、8K 12K VR播放 作为一个长期折腾的开发者,这段时间一直在找一款真正稳定、格式兼容性强、支持多音轨和外挂字幕的VR播放器。市面上不少播放器要么格式支持有限,要么在8K以上直接卡顿,更别说复杂场景下的字幕和音轨切换。 这次测试的是 Moon VR Video Player(月亮播放器)v835 + 2.8.18 中文版,整体体验确实比很多常见播放器更完整。下面做一次系统梳理,方便需要的朋友参考。 下载地址 链接:https://pan.quark.cn/s/7c80590579cf 一、

FAIR plus 机器人全产业链接会,链动全球智能新机遇

FAIR plus 机器人全产业链接会,链动全球智能新机遇

本文声明:本篇内容为个人真实体验分享,非商业广告,无强制消费引导。所有推荐仅代表个人感受,仅供参考,按需选择。 过往十年,中国机器人产业蓬勃发展。中国出品的核心部件得到了产业规模化的验证,机器人产品的整体制造能力也开始向全球输出。与此同时,机器人产业正在更加紧密地与人工智能融合,机器人从专用智能走向通用智能。 在此背景下,深圳市机器人协会打造了“FAIR plus机器人全产业链接会”,FAIR plus是一个专注于机器人全产业链技术和开发资源的平台,也是全球首个机器人开发技术展,以供应链和创新技术为切入点,推动全球具身智能机器人产业的发展。通过学术会议、技术标准、社区培育、供需对接等方式,创造人工智能+机器人各产业链环节的开发、产品、工程、方案等技术人员,以及有意引入机器人的场景方相关工艺、设备、信息技术人员线下见面的机会,达成合作,以有效促进机器人向智能化方向发展,连同提升产业整体能力的建设和配置。 2025年4月,首届“FAIR plus机器人全产业链接会”(FAIR plus 2025)以“智启未来链动全球”为主题,汇聚全球顶尖专家、企业领袖,

clawdbot (openclaw) + discord 机器人部署指南学习教程

clawdbot (openclaw) + discord 机器人部署指南学习教程

本文介绍了基于 ClawdBot(OpenClaw)框架在 Discord 平台部署 AI 对话机器人的完整流程。内容包括:Discord Application 与 Bot 的创建配置、OAuth2 权限管理、pnpm 全局安装、Daemon 服务配置、多模型 API 接入(支持智谱 GLM 等主流大模型)、Gateway 服务启动与调试等核心环节。 一、网络要求 * 魔法 * 确保网络能够访问Discord服务 * TUN模式(关键哦) 二、Discord平台配置 2.1 访问Discord开发者平台 访问地址:https://discord.com/developers/applications 2.2 创建应用程序 1. 登录Discord开发者平台