Hussam Khatib
07/28/2022, 6:22 AMif (role === Role.admin)
user = await prisma.user.findUnique({
where: {
id,
},
select: defaultAdminSelect,
});
if (role === Role.student)
user = await prisma.user.findUnique({
where: {
id,
},
select: defaultStudentSelect,
});Lloyd Richards
07/28/2022, 7:23 AMuser = await prisma.user.findUnique({
where: {
id,
},
select: role === Role.admin ? defaultAdminSelect : defaultStudentSelect,
});
or make some a specific getSelectByRole() if you have more then two rolesNurul
07/28/2022, 7:23 AMPromiseReturnType as mentioned in the guide to get correct return types for both the cases (admin and student)Hussam Khatib
07/28/2022, 7:44 AMIs the role property on the User that you are querying?yes.
As in, you're doing a nested query?Yes, this is my schema. If user is admin , the details field will be null, if student the selector will have nested data( from details which has 1-1 relation with another table)
model user {
id String @id @default(cuid())
role Role @default(student)
//...
details student?
}
Meanwhile I'm checking at the link provided by Nurul.Hussam Khatib
07/28/2022, 7:50 AMconst defaultAdminSelect = Prisma.validator<Prisma.userSelect>()({
id: true,
role: true,
email: true,
});Lloyd Richards
07/28/2022, 7:57 AMwhere with the roles for admin and then on fail default to the student:
const getUserOrAdmin = () => prisma.user.user.findUnique({
where: {
id,
role: Role.admin
},
select: defaultAdminSelect,
}).then((foundAdmin)=>foundAdmin ||
prisma.user.user.findUnique({
where: {
id,
},
select: defaultStudentSelect,
})
});
This could be done cleaner using fp_tsHussam Khatib
07/28/2022, 8:54 AMif (foundAdmin) return null; else return return .....selectStudent....
const getUserOrAdmin: (session: Maybe<Session>) => Promise<{
role: Role;
id: string;
email: string;
details: student | null; // works if foundAdmin is not returned
} | null>
and
if (foundAdmin) return foundAdmin;
const getUserOrAdmin: (session: Maybe<Session>) => Promise<{
role: Role;
id: string;
email: string;
// does not work as there can be a case in which foundAdmin can be returned , so that will be the only inferred types from prisma
} | null>Lloyd Richards
07/28/2022, 9:21 AMtype User = Admin | Student and then just check the role and get the correct type definition for the object.
https://dev.to/anthonyjoeseph/fp-ts-and-even-more-beautiful-api-calls-w-sum-types-53j0#unions-of-complex-types---sum-types
type Admin = {
role: Role.admin;
id: string;
email: string;
}
type Student= {
role: Role.student;
id: string;
email: string;
details: StudentDetails
}
const getUserOrAdmin: (session: Maybe<Session>) => Promise<Admin | Student | null>