P
Prisma2mo ago
Muchis

Get Correct Return Type when using Prisma ORM inside a method that accepts the client's args

Hi! So I have this simple example
model ExampleItem {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
//
name String
optionalField String?
messages ExampleMessage[]
//
shop String
shopifyStore ShopifyStore @relation(fields: [shop], references: [shop], onDelete: Cascade, onUpdate: Cascade)
}

model ExampleMessage {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
//
message String
//
exampleItemId Int
exampleItem ExampleItem @relation(fields: [exampleItemId], references: [id])
}
model ExampleItem {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
//
name String
optionalField String?
messages ExampleMessage[]
//
shop String
shopifyStore ShopifyStore @relation(fields: [shop], references: [shop], onDelete: Cascade, onUpdate: Cascade)
}

model ExampleMessage {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
//
message String
//
exampleItemId Int
exampleItem ExampleItem @relation(fields: [exampleItemId], references: [id])
}
// Method
export async function getExampleItem(
prismaArgs: Prisma.ExampleItemFindFirstArgs<DefaultArgs>,
db: PrismaClient
) {
try {
const exampleItem = await db.exampleItem.findFirst(prismaArgs);

// Do something else...

return exampleItem;
} catch (error) {
await handleError({ operation: 'catch', error });
}

return null;
}

const exampleItem = await getExampleItem({ where: { id: 1 }, include: { messages: true } }, db);
// Method
export async function getExampleItem(
prismaArgs: Prisma.ExampleItemFindFirstArgs<DefaultArgs>,
db: PrismaClient
) {
try {
const exampleItem = await db.exampleItem.findFirst(prismaArgs);

// Do something else...

return exampleItem;
} catch (error) {
await handleError({ operation: 'catch', error });
}

return null;
}

const exampleItem = await getExampleItem({ where: { id: 1 }, include: { messages: true } }, db);
The return value of getExampleItem is not being correctly typed from the context of include passed onto it (messages is non-existant). Also tried with select and it doesn't narrow the return. I might have an error in my prismaArgs type that I'm not aware of, can you shed some light here how can I correctly type this so I get the correct type returned depending on different prismaArgs ?)
No description
5 Replies
Muchis
Muchis2mo ago
Actually got really close now but I got an error here
Muchis
Muchis2mo ago
No description
Muchis
Muchis2mo ago
No description
Muchis
Muchis2mo ago
any leads here ?
Muchis
Muchis2mo ago
I kind of got it working but it has some nasty as castings
No description
Want results from more Discord servers?
Add your server