2

What type should i use inside Promise (instead of ?) ? I dont know exactly what will return, because of second argument - UserSelect.

async getOneUser(where: Prisma.UserWhereUniqueInput, userSelect?: Prisma.UserSelect):Promise<?> {
  const user = await this.prisma.user.findUnique({ where, select: { ...userSelect } })
  return user
}

I want to be able to select specific fields to pass in the select statement, instead of passing all of them by default.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
D Kramer
  • 41
  • 5
  • 1
    btw this has nothing to do with nestjs. It's just Prisma stuff. I'd drop that return type and see what typescript had inferred for me. (disclaimer: I didn't use Prisma before) – Micael Levi Jul 01 '23 at 23:20
  • Maybe something like `Pick`? – Bergi Jul 02 '23 at 12:57

3 Answers3

2

I made type with all possible selects and then use it with Partial inside Promise. I think it is the best option:

export type UserFullType = Prisma.UserGetPayload<{ select: { [K in keyof Required<Prisma.UserSelect>]: true } }>


async getOneUser(
        where: Prisma.UserWhereUniqueInput,
        userSelect: Prisma.UserSelect = {}
    ): Promise<Partial<UserFullType>> {
        const user = await this.prisma.user.findUnique({ where, select: { ...userSelect } })
        return user
    }

found useful info in this article

D Kramer
  • 41
  • 5
1

you may use any or Partial<T>

// here I decide to use Partial<User> as return
async getOneUser(
  where: Prisma.UserWhereUniqueInput,
  userSelect: Prisma.UserSelect,
): Promise<Partial<User>> {
  const user = await this.prisma.user.findUnique({
    where,
    select: { ...userSelect },
  });
  return user as Partial<User>;
}

and we can call it as following

// here I use uuid
await this.userService.getOneUser(
  { id: '064c1764-1ab0-4936-a735-e764fbfaa84e' },
  { id: true, _count: true, name: true },
);
0

This works in Versions prior 4.16.1, unfortunally it seems to be broken since then:

public async getOneUser<T extends Prisma.UserSelect | undefined>(where: Prisma.UserWhereUniqueInput, userSelect: T): Promise<Prisma.UserGetPayload<{select: T}>> {
    const user = await this.prisma.user.findUnique({ where, select: { ...userSelect } });
    return user;
}
user3817008
  • 613
  • 7
  • 13