Vallo
Vallo

Reputation: 1967

Prisma - use include as parameter

I have an entity with many relations and I want a function to handle the include property as parameter:

export const findById = async (id: number, include: Prisma.ClaimInclude | undefined = undefined) => {
    return dbClient.claim.findUnique({
        where: {
            id,
        },
        include,
    })
}

so I would use this function like this

const claim = await findById(claimId , { assignedTo: true, })

my problem is that now I cannot access the assignedTo property

Property 'assignedTo' does not exist on type 'Claim & {}'. Did you mean 'assignedToId'? ts(2551)

is there a way I could make this approach work, or do I need to have specific functions for each include type?

Thanks

Upvotes: 0

Views: 783

Answers (2)

Sergei Pechinov
Sergei Pechinov

Reputation: 11

Case with an optional parameter. It for my case, but you can rewrite for yourself.

static findGroupByGroupIDAndUserID<T extends Prisma.GroupInclude | undefined>(props: {
    groupID: string;
    userID: string;
    include?: T;
  }) {
    return Group.client.findUnique<{ where: Prisma.GroupWhereUniqueInput; include: T }>({
      where: { id: props.groupID, members: { some: { id: props.userID } }, deleted: false },
      include: props.include ?? (undefined as T),
    });
  }

Upvotes: 1

Vallo
Vallo

Reputation: 1967

This fixed my problem:

export function findById<S extends Prisma.ClaimInclude>(id: number, include: Prisma.Subset<S, Prisma.ClaimInclude>) {
  return dbClient.claim.findUnique<{ where; include: S }>({
    where: {
      id,
    },
    include,
  });
}

Upvotes: 2

Related Questions