Warm tip: This article is reproduced from stackoverflow.com, please click
graphql prisma prisma-graphql typescript nexus-prisma

Possibility to only retreive owners data with prisma2 and nexus

发布于 2020-05-08 03:50:26

When posting a query i want to retreive only the data that is assigned to the current user (id).

I retreive and set the userId with a middleware function that contains;

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

Base on the userId i need to filter the data from models like this;

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

so i want to return the equivalent to Addresses.filter(address => address.user.id === ctx.userId)

(the Addresses where the user.id is equal to the one set in the middleware)

for example something like this (this is made-up code so it doenst work)

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

Where the computedFilters filters the incoming query to match the requirements that are set in the where statement. So with this set it should only return the adresses and / or relations where user.id === ctx.userId.

I hope it is clear what i want to achieve, it doensn't have to be like this, the only thing that needs to be the same is the response in the most performant way.

I hope someone can help, i'm struggeling with the current issue for the last couple of weeks..

Questioner
RMCS
Viewed
9
RMCS 2020-02-25 23:41

I resolved the issue by editing the generated resolvers;

by replacing

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

with

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