The new Prisma client extensions provide a way to compute a custom field in the response.
e.g.
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient().$extends({
result: {
user: {
// Add a computed field called `nameAndAge` to the user
nameAndAge: {
needs: {
name: true,
age: true,
},
compute(user) {
return `${user.name} (${user.age}y)` + getdata();
},
},
},
},
});
const user = await prisma.user.findFirst();
console.log(user?.nameAndAge);
However, I want to call an async function from within the client like this:
async function getdata(){
return "external data here!"
}
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient().$extends({
result: {
user: {
// Add a computed field called `nameAndAge` to the user
nameAndAge: {
needs: {
name: true,
age: true,
},
compute(user) {
return `${user.name} (${user.age}y)` + getdata();
},
},
},
},
});
const user = await prisma.user.findFirst();
console.log(user?.nameAndAge);
However, this always returns a promise and I can't await the getdata() function in the return.
e.g.
Sonia Lomo (25y)[object Promise]
Is there a solution to this somehow ?
I also tried making the compute function asynchronous then awaiting the getdata() function. e.g.:
async compute(user) {
return `${user.name} (${user.age}y)` + await getdata();
},
However, the promise always returns as pending.
Promise { <pending> }