如何在客户端使用graphql-js调用GraphQL接口?有无轻量替代方案?
无框架依赖的TypeScript GraphQL客户端方案
一、直接基于graphql-js实现请求
graphql-js本身侧重GraphQL语法解析、验证逻辑,可配合原生HTTP工具(或轻量HTTP库)实现客户端请求,同时结合类型生成工具解决手动维护类型的繁琐问题:
1. 基础请求封装
用fetch(或axios)发起标准GraphQL POST请求,可选借助graphql-js做客户端查询验证,提前捕获错误:
import { parse, validate, GraphQLSchema } from 'graphql'; // 从类型生成文件导入预定义的Schema import { AppSchema } from './generated/schema'; async function graphQLRequest<T = any>( query: string, variables?: Record<string, unknown> ): Promise<T> { // 客户端查询验证(可选) const document = parse(query); const validationErrors = validate(AppSchema, document); if (validationErrors.length) { throw new Error(`Query validation failed: ${JSON.stringify(validationErrors)}`); } const response = await fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query, variables }), }); const result = await response.json(); if (result.errors) throw new Error(`GraphQL server error: ${JSON.stringify(result.errors)}`); return result.data as T; }
2. 自动生成TypeScript类型
使用graphql-codegen工具,完全无框架依赖,可从GraphQL Schema和查询文件自动生成类型:
- 安装开发依赖:
npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations - 创建
codegen.ts配置文件,指定Schema来源(服务端端点或本地文件)、查询文件路径、输出目录 - 运行生成命令后,查询的返回值和变量都会自动带上强类型,无需手动编写。
二、轻量无框架GraphQL客户端库
如果不想自己封装HTTP逻辑,这些库完全不依赖React/Angular:
1. graphql-request
超轻量的极简客户端,仅依赖graphql,API直观易用:
import { request, gql } from 'graphql-request'; const endpoint = '/graphql'; // 结合graphql-codegen生成的类型,返回值自动带TS类型 async function getUser(userId: string) { const query = gql` query GetUser($id: ID!) { user(id: $id) { id name email } } `; return request(endpoint, query, { id: userId }); }
2. urql Core
urql的核心库@urql/core不带任何框架绑定,支持缓存、请求重试等实用功能,同时兼容graphql-codegen:
import { createClient, gql } from '@urql/core'; const client = createClient({ url: '/graphql' }); async function getUsers() { const result = await client.query(gql` query GetUsers { users { id name } } `).toPromise(); if (result.error) throw result.error; return result.data.users; }
三、Apollo的无框架用法
Apollo并非必须依赖React——你可以只安装核心库@apollo/client/core,无需安装React相关包,它支持缓存、批量请求等高级特性:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client/core'; const client = new ApolloClient({ uri: '/graphql', cache: new InMemoryCache(), // 不需要缓存可直接移除该配置 }); async function fetchPosts() { const { data } = await client.query({ query: gql` query GetPosts { posts { id title content } } `, }); return data.posts; }
内容的提问来源于stack exchange,提问作者Sasha Shpota
相关产品推荐
相关产品推荐

