如何在 React 中使用 Apollo Client 连接到 NestJS GraphQL 服务?

解读

面试官问“怎么连”,不是让你背官网代码,而是想看三件事:

  1. 你是否真的在产线搭过这套链路(NestJS 后端 + React 前端),知道国内网络、证书、代理、CORS、鉴权这些“坑”;
  2. 你是否理解 GraphQL 从 Schema → Resolver → DataLoader → React Component 的完整数据闭环;
  3. 你是否能把“开发体验”做到可测试、可灰度、可回滚,而不是跑通 Demo 就完事。

因此,回答时要体现“工程化落地”视角:环境区分、代码生成、错误边界、性能监控、Serverless 场景兼容,一个都不能少。

知识点

  1. NestJS GraphQL 模块两种模式:Code First(TypeGraphQL)与 Schema First,国内团队 70% 选 Code First,因为装饰器对 TypeScript 友好,且能直接生成前端类型。
  2. Apollo Client 3.x 的链路设计:ApolloLink 拆分“网络层、重试层、鉴权层、日志层”,国内常用 @apollo/client + apollo-link-error + apollo-link-retry 组合。
  3. 国内必踩的 CORS:如果前端走 Vite 本地 5173,后端在 3000,必须显式配置 origin: ['http://localhost:5173', 'https://dev.xxx.cn'],且 credentials: 'include',否则 Cookie 带不过去。
  4. 鉴权方案:BFF 层统一走 Cookie + SameSite=strict;若需嵌入小程序,再走 JWT+Header,Apollo 端用 setContext 动态注入 Authorization。
  5. 代码生成:国内主流用 @graphql-codegen/cli,CI 阶段拉后端 /.well-known/schema.gql,自动生成 types.ts + react-apollo hooks,避免手写 TypedDocumentNode。
  6. 分包优化:React 路由懒加载时,把 Apollo 缓存做成单例,防止重复 new InMemoryCache() 导致缓存击穿。
  7. Serverless 场景:Next.js 国内多走 Vercel 边缘函数或阿里云函数计算,需把 Apollo Client 初始化放进 getServerSideProps,并关闭 ssrMode: true,防止冷启动重复建连。
  8. 性能监控:阿里 SLS / 腾讯 RUM 会上报 GraphQL 错误码,需在 apollo-link-error 里把 { graphQLErrors, networkError, operationName } 序列化后打到日志。

答案

下面给出一套可直接落地的“三步九检查”方案,面试官如追问细节,可逐层展开。

第一步:NestJS 侧确保 GraphQL 端点可访问

  1. 安装依赖
    npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express
  2. 在 AppModule 注册
    GraphQLModule.forRoot<ApolloDriverConfig>({
    driver: ApolloDriver,
    autoSchemaFile: join(process.cwd(), 'schema.gql'),
    sortSchema: true,
    cors: {
    origin: ['http://localhost:5173', 'https://dev.xxx.cn'],
    credentials: true,
    },
    context: ({ req, res }) => ({ req, res }),
    })
  3. 启动后访问 http://localhost:3000/graphql 能看到 GraphQL Playground,说明服务已就绪。

第二步:React 侧创建“环境感知”的 Apollo Client

  1. 封装 createApolloClient(env: 'local' | 'dev' | 'prod')
    • uri: 根据 window.ENV.GRAPHQL_URI || '/graphql' 动态拼接,解决本地代理与线上网关路径不一致问题。
    • cache: new InMemoryCache({
      typePolicies: {
      Query: {
      fields: {
      // 关键:分页场景用 offsetLimitPagination()
      articles: offsetLimitPagination(),
      },
      },
      },
      })
    • link: from([
      // 1. 日志链路
      new ApolloLink((operation, forward) => {
      operation.setContext({ start: Date.now() });
      return forward(operation).map((response) => {
      const cost = Date.now() - operation.getContext().start;
      if (cost > 800) console.warn(Slow query ${operation.operationName}: ${cost}ms);
      return response;
      });
      }),
      // 2. 错误上报
      onError(({ graphQLErrors, networkError, operation }) => {
      if (graphQLErrors)
      graphQLErrors.forEach(({ extensions }) => {
      window.TRACK?.logError({ code: extensions?.code, operation: operation.operationName });
      });
      }),
      // 3. 鉴权
      setContext((_, { headers }) => ({
      headers: {
      ...headers,
      authorization: getToken() ? Bearer ${getToken()} : '',
      },
      })),
      // 4. 重试
      new RetryLink({ attempts: { max: 3, retryIf: (error) => !!error && Math.random() > 0.5 } }),
      // 5. HTTP
      createUploadLink({
      uri: ${getBaseUrl()}/graphql,
      credentials: 'include',
      }),
      ])
  2. 在 src/main.tsx 只初始化一次
    const client = createApolloClient(import.meta.env.MODE as any);
    ReactDOM.createRoot(document.getElementById('root')!).render(
    <ApolloProvider client={client}>
    <App />
    </ApolloProvider>
    )

第三步:组件层使用生成的 hooks

  1. codegen.yml
    schema: http://localhost:3000/graphql
    documents: src/**/*.graphql
    generates:
    src/gql/types.ts:
    plugins: [typescript]
    src/gql/operations.ts:
    preset: import-types
    presetConfig: typesPath: ./types
    plugins: [typescript-operations, typescript-react-apollo]
  2. 业务组件
    import { useArticlesQuery } from '@/gql/operations';
    export const ArticleList: React.FC = () => {
    const { data, loading, error } = useArticlesQuery({
    variables: { first: 20 },
    fetchPolicy: 'cache-and-network', // 国内弱网优先读缓存
    });
    if (error) return <ErrorBlock retry={() => refetch()} />;
    return <List data={data?.articles.edges} />;
    }

九项检查清单(面试时主动说出来,体现工程深度)

  1. 后端是否开启 introspection: false(生产关闭,预发打开)。
  2. 前端是否对 GraphQL 错误码做国际化映射(extensions.code = FORBIDDEN → “无权限”)。
  3. 上传文件是否走 graphql-upload-minimal,并在 apollo 侧用 createUploadLink。
  4. 是否对大数据列表开启 fetchPolicy: 'cache-first' + pagination merge 函数,防止重复请求。
  5. 是否把 Apollo 缓存快照做 SSR 注水,防止 Next.js 首屏闪动。
  6. 是否在 CI 加一层“schema 校验”,当前端 documents 出现 breaking change 时自动 fail。
  7. 是否对网关做 GraphQL Query Complexity 限流,防止一次查 10w 条把数据库打挂。
  8. 是否在移动端接入 apollo-link-queue,弱网时把 mutation 排队,恢复后批量发送。
  9. 是否把 GraphQL 路径纳入公司统一网关,方便做灰度、A/B、流量染色。

拓展思考

  1. 如果公司把 NestJS 部署在阿里云函数计算,冷启动 3s,前端首屏如何做到“无白屏”?
    思路:把静态 HTML 走 CDN 边缘缓存,DataLoader 层用 Redis + DataLoader 做预聚合,函数实例预热由定时触发器每 5 分钟 ping 一次;Apollo 侧开启 ssrMode: true,把缓存快照序列化到 HTML,首屏直接 renderToString,省去一次 roundtrip。

  2. 微前端场景下,子应用 A(React17)和子应用 B(React18)共用一套 NestJS GraphQL,如何防止多版本 Apollo 缓存冲突?
    思路:在 qiankun 的 sandbox 里把 Apollo Client 实例挂在 window.POWERED_BY_QIANKUN ? 'subA' : 'subB' 命名空间下,主应用负责下发 schema 版本号,子应用根据版本号决定是复用缓存还是清空重建;同时用 webpack module federation 把 @apollo/client 提取为 shared singleton,确保全局只有一份 InMemoryCache。

  3. 面试官最后追问“如果我一个 Query 返回 10M 数据,怎么优化”?
    别只说“分页”。标准答案:

    • 后端用 Field-Level 的 @HasRoles + DataLoader 做权限裁剪,减少无效字段;
    • 开启 Apollo 的 @defer 与 @stream,把非关键片段拆成增量响应;
    • 前端用 graphql-query-complexity 插件提前估算 cost,超过阈值自动拆成多个小请求;
    • 网络层开启 gzip + brotli,NestJS 侧加 fastify-compress,阿里云 CDN 再压一次,10M 可降到 800K;
    • 最后把大字段(如富文本)拆成独立对象存储 URL,GraphQL 只返回链接,前端按需懒加载。