How to get the return Type of a query with relations?

- Imagine having 2 tables: Posts and Users - there is a relation between Posts and users, since 1 user can write several posts. So we define this relation. - now I write a query to retrieve the user and all his/her posts with the syntax:
const user = await db.query.findFirst({
where: .....
with: {
posts: true
}
});
const user = await db.query.findFirst({
where: .....
with: {
posts: true
}
});
How can I "extract" / "infer" the type of user beforehand? My goal is to be able to write something like:
class myStore {
public user: UserWithPosts;

loadUser(id: number){
this.user = await db.query.findFirst({
where: .....
with: {
posts: true
}
});
}
}
class myStore {
public user: UserWithPosts;

loadUser(id: number){
this.user = await db.query.findFirst({
where: .....
with: {
posts: true
}
});
}
}
No description
2 Replies
medromo
medromo12mo ago
I would create an external helper function that makes the db query and then use the return type for the public user variable
const getUser = async (id: number) => {
return await db.query.users.findFirst({
where: .....,
with: {
posts: true
}
});
};

type UserWithPosts = Awaited<ReturnType<typeof getUser>>;

class myStore {
public user: UserWithPosts;

async loadUser(id: number) {
this.user = await getUser(id);
};
};
const getUser = async (id: number) => {
return await db.query.users.findFirst({
where: .....,
with: {
posts: true
}
});
};

type UserWithPosts = Awaited<ReturnType<typeof getUser>>;

class myStore {
public user: UserWithPosts;

async loadUser(id: number) {
this.user = await getUser(id);
};
};
This should do the trick
pMullot
pMullot12mo ago
Great idea! I'll try that right away! Thanks a lot!
Want results from more Discord servers?
Add your server