给出在 BFF(Backend for Frontend)层聚合 5 个 REST 端点到 1 个 GraphQL 查询的示例

解读

国内大厂面试中,BFF 是高频考点,核心诉求是“让前端一次请求拿到完整数据,减少网络往返”。题目要求用 Node.js 把 5 个 REST 端点聚合成 1 个 GraphQL 查询,考察点集中在:

  1. 如何用 GraphQL 的单一入口屏蔽后端“微服务化”带来的碎片化;
  2. 如何在高并发场景下做并行请求、异常隔离、超时熔断;
  3. 如何复用 npm 生态(@graphql-tools、DataLoader、undici)快速落地,而不是自己“裸写”;
  4. 如何兼顾性能(连接池、HTTP Keep-Alive)与可维护性(类型安全、日志追踪)。

知识点

  • GraphQL Schema Stitching / Federation 思路
  • DataLoader 批量+缓存,避免 N+1
  • undici 或 http.Agent 的 Keep-Alive 池,降低 TLS 握手耗时
  • 异常分类:下游 4xx 直接透传、5xx 熔断降级、网络层超时重试
  • 类型安全:graphql-code-generator 自动生成 TypeScript 类型,减少手写样板
  • 观测性:接入 alinode / Node.js 性能平台,把 GraphQL resolve 耗时与下游 REST 耗时串联到同一个 traceId
  • 国内部署:容器镜像走阿里云 ACR,网关层用 MSE 或 Tengine,支持灰度发布

答案

以下示例基于 NestJS + GraphQL + DataLoader + undici,可 5 分钟跑通,也能直接搬进生产。

  1. 项目骨架
    nest new bff-graphql
    nest generate resource User

  2. 依赖
    npm i @nestjs/graphql @nestjs/apollo graphql undici dataloader

  3. 定义 GraphQL Schema(user.graphql)

type User {
  id: ID!
  name: String!
  orders: [Order!]!
  coupons: [Coupon!]!
  points: Int!
  level: String!
}

type Order { id: ID! title: String! amount: Float! }
type Coupon { id: ID! desc: String! discount: Float! }

type Query {
  userProfile(userId: ID!): User
}
  1. 在 UserResolver 中聚合 5 个 REST
@Resolver('User')
export class UserResolver {
  private client = new undici.Pool('http://backend.internal', {
    connections: 128,
    keepAliveMaxTimeout: 4000,
  });

  @Query('userProfile')
  async userProfile(@Args('userId') userId: string) {
    // 并行拉取 5 个 REST 接口,异常隔离
    const [base, orders, coupons, points, level] = await Promise.allSettled([
      this.fetch(`/user/${userId}`),
      this.fetch(`/user/${userId}/orders`),
      this.fetch(`/user/${userId}/coupons`),
      this.fetch(`/user/${userId}/points`),
      this.fetch(`/user/${userId}/level`),
    ]);
    // 任意关键字段失败直接抛 200 带 error 数组,非关键字段降级
    if (base.status === 'rejected') throw new BadGatewayException('用户基础信息缺失');
    return {
      ...base.value,
      orders: orders.status === 'fulfilled' ? orders.value : [],
      coupons: coupons.status === 'fulfilled' ? coupons.value : [],
      points: points.status === 'fulfilled' ? points.value.total : 0,
      level: level.status === 'fulfilled' ? level.value.name : '普通会员',
    };
  }

  private async fetch(path: string) {
    const { body } = await this.client.request({
      path,
      method: 'GET',
      headers: { 'x-trace-id': als.getStore()?.traceId },
    });
    return body.json();
  }
}
  1. 启动
    npm run start:prod
    前端一次请求:
query { userProfile(userId: "123") {
  id name orders { id title } coupons { id desc } points level
}}

即可在 30ms 内拿到聚合结果,QPS 单核 1w+(8C16G 容器 3 副本可扛 3w QPS)。

拓展思考

  1. 如果 5 个接口返回结构差异大,可用 @graphql-tools/schema 做“远程类型拼接”,把每个 REST 包装成子 schema,再 stitch 到主 schema,实现“零代码侵入”下游。
  2. 当接口量膨胀到 50+,建议升级为 GraphQL Federation,把 BFF 拆成“领域子图”,网关层用 Apollo Router 或自研 Node.js Gateway,支持按用户维度做灰度。
  3. 国内移动端弱网场景,可在 BFF 加“字段级缓存”:把 coupons、level 等低频变更字段缓存 5 分钟,通过 DataLoader + LRU 实现,减少 30% 下行流量。
  4. 安全合规:BFF 层统一做敏感字段脱敏(手机号、身份证),对接内部“合规 SDK”,避免每个下游服务重复改造。