定义接口 Node { id: ID! } 并让 User、Post 实现它

解读

在国内一线/二线互联网公司的 GraphQL 面试中,这道题出现的频率极高,面试官真正想考察的是你对 GraphQL 类型系统的“接口(Interface)”机制是否理解到位,以及能否写出可落地的 Schema 与 Resolver。
很多候选人只写 Schema 不写 Resolver,或者把 Node 接口当成普通对象类型去“继承”,都会直接扣分。
Node 接口是 GraphQL 做“全局唯一标识”查询(node(id: ID!))的前提,也是 Relay 规范的核心,答出“全局 ID 策略 + resolveType”才算完整闭环。

知识点

  1. 接口(Interface)
    GraphQL 的接口是抽象类型,只能定义字段,不能定义实现,由对象类型通过 implements 关键字实现。
  2. 实现规则
    实现接口的对象类型必须显式列出接口所有字段,字段名、类型、参数、非空约束必须完全兼容。
  3. resolveType 与 isTypeOf
    运行时 GraphQL 需要知道“一个具体值到底属于哪个实现类型”,必须在 resolver 层提供 resolveType(接口端)或 isTypeOf(对象类型端),否则执行会抛 Abstract type Node must resolve to an Object type at runtime。
  4. 全局 ID 规范(Relay Node)
    国内大厂在 BFF 网关层普遍要求 ID 全局唯一且可反解类型,通常用 base64(TypeName:dbId) 拼接,node(id: ID!) 查询必须能反解出类型与主键,再分发到对应表/微服务。
  5. 代码组织
    在真实项目中,Schema 与 Resolver 分离,Node 接口的 resolver 单独放在 src/graphql/interface/node.js,User/Post 的 resolver 放在各自模块,通过 context.dataloaders 解决 N+1。

答案

以下给出可直接跑通的 SDL + Resolver 示例,Node 接口、User/Post 实现、全局 ID 编解码、node 根查询 全部包含,面试官可逐行追问。

# schema.graphql
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  name: String!
  age: Int
}

type Post implements Node {
  id: ID!
  title: String!
  author: User!
}

type Query {
  node(id: ID!): Node
  user(id: ID!): User
  post(id: ID!): Post
}
// resolvers.js
const { GraphQLID } = require('graphql');
const { fromGlobalId, toGlobalId } = require('./utils/globalId');

const resolvers = {
  // 根查询
  Query: {
    node: async (_, { id }, ctx) => {
      const { type, dbId } = fromGlobalId(id);   // 反解:User:123 -> {type:'User', dbId:'123'}
      if (type === 'User') return ctx.userLoader.load(dbId);
      if (type === 'Post') return ctx.postLoader.load(dbId);
      return null;
    },
    user: (_, { id }, ctx) => ctx.userLoader.load(id),
    post: (_, { id }, ctx) => ctx.postLoader.load(id),
  },

  // 接口解析
  Node: {
    __resolveType(obj) {
      // obj 来自数据库,内含 __typename 或根据字段推断
      if (obj.name) return 'User';
      if (obj.title) return 'Post';
      return null;
    },
  },

  // 对象类型
  User: {
    id: parent => toGlobalId('User', parent.id), // 编码:User:123 -> VXNlcjoxMjM=
  },
  Post: {
    id: parent => toGlobalId('Post', parent.id),
    author: (parent, _, ctx) => ctx.userLoader.load(parent.authorId),
  },
};

module.exports = resolvers;
// utils/globalId.js
const base64 = str => Buffer.from(str, 'utf8').toString('base64');
const unbase64 = str => Buffer.from(str, 'base64').toString('utf8');

exports.toGlobalId = (type, id) => base64(`${type}:${id}`);
exports.fromGlobalId = globalId => {
  const [type, id] = unbase64(globalId).split(':');
  return { type, id };
};

关键点强调

  • Node 接口字段必须显式在 User/Post 中再次出现,不能省略。
  • __resolveType 必须返回字符串字面量,不能返回变量或 null(运行时抛错)。
  • 全局 ID 必须可逆,否则 node 查询无法分发;国内大厂普遍要求带类型前缀,方便灰度、埋点、审计。
  • DataLoader 批量加载 在 resolver 层必须落地,否则面试会被追问“如果一次查询 100 个节点怎么防 N+1”。

拓展思考

  1. 多接口继承
    GraphQL 允许一个对象类型实现多个接口,例如 type User implements Node & Timestampable,国内中台场景常用 Timestampable { createdAt updatedAt } 做统一审计字段。
  2. Union 与 Interface 区别
    面试官可能追问“为什么不用 union SearchResult = User | Post”,接口强调字段共性,Union 仅做类型聚合,两者 resolver 策略不同。
  3. 微服务场景下 node 查询性能
    如果 User、Post 在不同服务,node 查询会变成扇出请求,国内大厂会在网关层做 ID 路由表 或 Redis 布隆过滤器 先定位服务,再转发,面试可主动提及“我们用了服务标签 + 本地缓存把扇出降到 O(1)”。
  4. 权限与数据隔离
    全局 ID 透明编码可能泄露内部表主键,国内金融、安全敏感场景会再加一层 AES 对称加密,并在 node resolver 里做 RBAC 数据权限裁剪,面试提到这一点可体现安全意识。