前端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

旧安卓手机别扔!用KSWEB搭个人博客,搭配外网访问超香

旧安卓手机别扔!用KSWEB搭个人博客,搭配外网访问超香

KSWEB 作为安卓端轻量级 Web 服务器,核心功能是提供 PHP、MySQL 运行环境,能轻松部署 Typecho、WordPress 等博客系统,Termux 则可辅助管理内网穿透服务;这类工具特别适合预算有限的学生、个人博主,或是想折腾闲置设备的数码爱好者,优点也很突出 —— 对硬件要求极低,1GB 内存就能运行,旧款红米、华为畅享等机型都能适配,而且内置的运行环境无需手动配置,新手也能快速上手。 使用这套工具时也有不少需要注意的地方,比如手机要长期插电并连接稳定 Wi-Fi,否则服务容易中断;还要给 KSWEB 和 Termux 关闭电池优化、放开存储权限,我用小米手机测试时就因为没关后台限制,导致 Apache 服务频繁被系统杀掉,折腾了好一会儿才排查出问题;另外非 Root 机型也能使用,但部分文件权限操作会稍显繁琐。 不过仅靠 KSWEB 部署完博客后,只能在局域网内访问,这会带来很多不便:比如在家用电脑能连手机看博客,

Claude Code Viewer: 打造 Web 端 Claude Code 会话管理利器

Claude Code Viewer: 打造 Web 端 Claude Code 会话管理利器 当 Claude Code 成为日常开发标配,如何更高效地管理会话历史、分析对话流程就成了开发者的新需求。Claude Code Viewer 应运而生——一个功能完备的 Web 端 Claude Code 客户端。 背景介绍 Claude Code 是 Anthropic 推出的 AI 编程助手,但其原生的会话管理能力相对基础。大多数开发者面临以下痛点: * 会话历史难以追溯和检索 * 无法在移动设备上方便地查看会话 * 多人协作时难以共享会话内容 * 缺乏对会话流程的全局视角 Claude Code Viewer 正是为解决这些问题而生的开源项目。它采用 Web 架构设计,专注于会话日志的完整分析,通过严格的数据校验和渐进式展示 UI,让每一个对话细节都清晰可见。

【芯片解读】TI AFE5816:16通道超声波模拟前端 (AFE) 深度详解

【芯片解读】TI AFE5816:16通道超声波模拟前端 (AFE) 深度详解

【芯片解读】TI AFE5816:16通道超声波模拟前端 (AFE) 深度详解 简介 在医疗超声成像、无若检测(NDT)以及声纳应用中,模拟前端(AFE)的性能直接决定了成像的质量。Texas Instruments (TI) 的 AFE5816 是一款高度集成的 16 通道模拟前端解决方案,专为需要高性能、低功耗和小尺寸的便携式及高端超声波系统设计。 国产类似产品为海思的AC9810-32,该产品与TI的AFE5832功能相似,为32通道AFE,海思后续还有64通道的产品推出。 1. 核心特性概览 (Key Features) AFE5816 是一个多芯片模块(MCM),集成了两个晶圆:VCA(压控放大器)和 ADC_CONV(模数转换)。其主要特性如下: * 高集成度:单芯片集成 16 个通道,每个通道包含衰减器、LNA、LPF、

【粉丝福利社】扣子(Coze) Skills+OpenClaw 实战:零基础玩转AI智能体

【粉丝福利社】扣子(Coze) Skills+OpenClaw 实战:零基础玩转AI智能体

💎【行业认证·权威头衔】 ✔ 华为云天团核心成员:特约编辑/云享专家/开发者专家/产品云测专家 ✔ 开发者社区全满贯:ZEEKLOG博客&商业化双料专家/阿里云签约作者/腾讯云内容共创官/掘金&亚马逊&51CTO顶级博主 ✔ 技术生态共建先锋:横跨鸿蒙、云计算、AI等前沿领域的技术布道者 🏆【荣誉殿堂】 🎖 连续三年蝉联"华为云十佳博主"(2022-2024) 🎖 双冠加冕ZEEKLOG"年度博客之星TOP2"(2022&2023) 🎖 十余个技术社区年度杰出贡献奖得主 📚【知识宝库】 覆盖全栈技术矩阵: ◾ 编程语言:.NET/Java/Python/Go/Node… ◾ 移动生态:HarmonyOS/iOS/Android/小程序 ◾ 前沿领域: