1

我正在使用 Mikro-ORM 和 type-graphql 创建一个 GraphQL 服务器,对于某些 GraphQL 查询,我需要根据查询参数的无效性为查找操作动态创建“where”参数。我的问题是关于“where”参数的输入。

@Query(() => [Topic])
  topics(
    @Ctx() { em }: Context,
    @Arg("filter") { subject_id, approved }: TopicArgs
  ): Promise<Topic[]> {
    const where: any = {};
    if (approved) where.approved = approved;
    return em.find(Topic, filter);
  }

我尝试FilterQuery<Topic>基于调用签名使用,find但这会在赋值行引发“类型上不存在属性”错误,并在调用find函数行引发“类型不兼容”错误。any除了在代码片段中使用 like 之外,还有其他解决方案吗?

4

1 回答 1

0

如果参数具有正确的类型,您可以尝试这样的操作来简化输入问题:

@Query(() => [Topic])
  topics(
    @Ctx() { em }: Context,
    @Arg("filter") { subject_id, approved }: TopicArgs
  ): Promise<Topic[]> {
    return em.find(Topic, {
       ...(approved ? { approved } : {}),
       ...(subject_id ? { subject_id } : {})
    });
  }

好处是您可以组合更复杂的条件,并在未提供参数时提供默认查询。

如果您仍想为 where 过滤器声明一个显式对象,您应该FilterQuerymikro-orm.

然后你应该能够像这样声明它:

@Query(() => [Topic])
  topics(
    @Ctx() { em }: Context,
    @Arg("filter") { subject_id, approved }: TopicArgs
  ): Promise<Topic[]> {
    const where: FilterQuery<Topic> = {};
    if (approved) where.approved = approved;
    return em.find(Topic, where);
  }
于 2022-01-25T21:27:00.650 回答