Reuse with in multiple queries
This is what I currently do, but I would like to be able to reuse the
I would like something like this, but when I do it this way I end up with wrong types
with
clause in multiple queries. Is there a way to do this?
export const matchesWithPlayers = () =>
db.query.matches.findMany({
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});
export const playerMatches = (userId: string) =>
db.query.matches.findMany({
where: or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)),
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});
export const matchesWithPlayers = () =>
db.query.matches.findMany({
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});
export const playerMatches = (userId: string) =>
db.query.matches.findMany({
where: or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)),
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});
const withPlayers = {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
};
export const matchesWithPlayers = () =>
db.query.matches.findMany({
with: withPlayers,
});
export const playerMatches = (userId: string) =>
db.query.matches.findMany({
where: or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)),
with: withPlayers,
});
const withPlayers = {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
};
export const matchesWithPlayers = () =>
db.query.matches.findMany({
with: withPlayers,
});
export const playerMatches = (userId: string) =>
db.query.matches.findMany({
where: or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)),
with: withPlayers,
});
1 Reply
This is how I would do it:
The only difference between the two is just the where. And its only used if the userId is provided
export const getMatches = (userId?: string) =>
db.query.matches.findMany({
where: userId ? or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)) : undefined,
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});
export const getMatches = (userId?: string) =>
db.query.matches.findMany({
where: userId ? or(eq(matches.playerOne, userId), eq(matches.playerTwo, userId)) : undefined,
with: {
playerOne: {
columns: {
id: true,
name: true,
elo: true,
},
},
playerTwo: {
columns: {
id: true,
name: true,
elo: true,
},
},
},
});