You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJs中@ResolveField如何访问父级的父级(User对象)

解决NestJS GraphQL中Profile字段解析器访问User对象的问题

针对你遇到的ProfileResolver中无法通过@Parent/@Root获取User对象的问题,提供以下几种可行方案:

方案1:把isEditable解析器移到UserResolver里

既然isEditable的判断依赖User的role,直接在UserResolver中定义这个字段的解析器,此时@Parent会直接拿到完整的User对象:

@Resolver(() => User)
export class UserResolver {
  @ResolveField('isEditable', () => Boolean, { nullable: false })
  async isEditable(@Parent() user: User) {
    // 直接用user.role做判断逻辑
    return user.role === 'ADMIN'; // 替换成你的实际判断规则
  }
}

注:这种写法不会改变Schema结构,isEditable仍然属于Profile类型,NestJS会自动关联到正确的字段上。

方案2:解析Profile时附带User引用

在UserResolver处理profile字段时,把User对象附加到返回的Profile实例上,之后在ProfileResolver里就能从@Parent拿到带User引用的Profile:

  1. 修改UserResolver的profile解析逻辑:
@Resolver(() => User)
export class UserResolver {
  constructor(private readonly profileService: ProfileService) {}

  @ResolveField(() => Profile)
  async profile(@Parent() user: User) {
    const profile = await this.profileService.getProfileByUserId(user._id);
    // 给Profile加个临时属性存User,用类型断言避免TS报错
    (profile as Profile & { _user: User })._user = user;
    return profile;
  }
}
  1. 在ProfileResolver中获取User:
@Resolver(() => Profile)
export class ProfileResolver {
  @ResolveField(() => Boolean, { nullable: false })
  async isEditable(@Parent() profile: Profile & { _user: User }) {
    // 通过profile._user访问User的role
    return profile._user.role === 'ADMIN'; // 替换成你的实际判断规则
  }
}

方案3:用@Root拿根对象(仅适用于根为User的请求)

如果你的请求根对象就是User(比如查询getUser(): User),直接用@Root就能拿到User对象:

@Resolver(() => Profile)
export class ProfileResolver {
  @ResolveField(() => Boolean, { nullable: false })
  async isEditable(@Root() user: User) {
    return user.role === 'ADMIN'; // 替换成你的实际判断规则
  }
}

注:如果Profile嵌套在其他对象下,@Root拿到的就不是User了,这种场景别用这个方案。

方案4:通过Context传递User

在请求流程里把User存到GraphQL Context中,之后在ProfileResolver里从Context取出:

  1. 在UserResolver的profile解析器中存Context:
@Resolver(() => User)
export class UserResolver {
  constructor(private readonly profileService: ProfileService) {}

  @ResolveField(() => Profile)
  async profile(@Parent() user: User, @Context() context) {
    // 把User放进Context
    context.currentUser = user;
    return this.profileService.getProfileByUserId(user._id);
  }
}
  1. 在ProfileResolver中取Context里的User:
@Resolver(() => Profile)
export class ProfileResolver {
  @ResolveField(() => Boolean, { nullable: false })
  async isEditable(@Context() context) {
    const user = context.currentUser;
    return user.role === 'ADMIN'; // 替换成你的实际判断规则
  }
}

注:如果同一个请求里有多个User对象,Context里的currentUser会被覆盖,只适合单User的请求场景。


内容的提问来源于stack exchange,提问作者Jeremias Nater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:54:51