仅使用 prisma 和 nexus 检索所有者数据的可能性

Posted

技术标签:

【中文标题】仅使用 prisma 和 nexus 检索所有者数据的可能性【英文标题】:Possibility to only retreive owners data with prisma2 and nexus 【发布时间】:2020-06-06 14:01:41 【问题描述】:

发布查询时,我只想检索分配给当前用户 (id) 的数据。

我使用包含的中间件函数检索并设置userId

const userId = tokenPayload['claims']['uid'];
ctx.userId = userId;

基于userId,我需要从这样的模型中过滤数据;

model Address 
  id                   String      @id @default(uuid())
  name                 string
  ...
  user                 User

所以我想返回等价于Addresses.filter(address => address.user.id === ctx.userId)

Addressesuser.id 等于中间件中的一组)

例如这样的事情(这是编造的代码,所以它确实有效)

plugins: [nexusPrismaPlugin(
    
      computedInputs: 
      ...
      ,
      computedFilters: 
        addresses: ( ctx ) => ( where:  user:  id: ctx.userId   ),
        relations: ( ctx ) => ( where:  user:  id: ctx.userId   ),
        ...
      
    
  )],

computedFilters 过滤传入查询以匹配where 语句中设置的要求。 所以有了这个集合,它应该只返回adresses和/或relations,其中user.id === ctx.userId

我希望很清楚我想要实现的目标,它不必是这样的,唯一需要相同的是以最高效的方式响应。

我希望有人能提供帮助,过去几周我一直在努力解决当前的问题..

【问题讨论】:

不能在batchRead上使用过滤器吗?请参阅:github.com/prisma-labs/nexus-prisma#batch-filtering 和 github.com/prisma-labs/nexus-prisma#filtering 你能解决这个问题吗? @RMCS 【参考方案1】:

我通过编辑生成的解析器解决了问题;

通过替换

t.crud.addresses(filtering: true, ordering: true);

t.list.field('addresses', 
      type: 'Address',
      resolve: (_parent, _args, ctx) => 
        return ctx.prisma.address.findMany(
          where: 
            user: 
              id: ctx.userId
            
          
        )
      
    );

【讨论】:

以上是关于仅使用 prisma 和 nexus 检索所有者数据的可能性的主要内容,如果未能解决你的问题,请参考以下文章

使用 GraphQL、Nexus 和 Prisma 优化 SQL 查询

GraphQL/Prisma 订阅仅针对 DELETE 触发

如何使用 prisma 2 或 3 和 nexus 模式生成同时生成生成的 crud 和“ondelete 级联”

Prisma nexus crud 未正确生成模式

如何将数组作为参数传递给 Nexus?如何使用 Prisma 从这个数组创建多个对象?

将自定义 GraphQL 解析器和类型添加到 Prisma/Nexus 架构中