Reuse with in multiple queries

This is what I currently do, but I would like to be able to reuse the 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,
},
},
},
});
I would like something like this, but when I do it this way I end up with wrong types
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
Angelelz
Angelelz14mo ago
This is how I would do it:
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,
},
},
},
});
The only difference between the two is just the where. And its only used if the userId is provided
Want results from more Discord servers?
Add your server