K
Kysely2mo ago
UV

Dynamic case when expression

I was struggling to figure out how to dynamically build a case expression. At the moment I've just got hardcoded for 6 indexes which doesn't seem like a good approach.
export async function healParty(userId: string) {
// Array of the user's party
const partyBeasts = await getBeastParty(userId);
const beastIds = partyBeasts.map((beast) => beast.id);

await db
.updateTable("beast")
.set((eb) => ({
currentHp: eb
.case()
.when("partyIndex", "=", 0)
.then(partyBeasts.find((b) => b.partyIndex === 0)?.stats.maxHp)
.when("partyIndex", "=", 1)
.then(partyBeasts.find((b) => b.partyIndex === 1)?.stats.maxHp)
.when("partyIndex", "=", 2)
.then(partyBeasts.find((b) => b.partyIndex === 2)?.stats.maxHp)
.when("partyIndex", "=", 3)
.then(partyBeasts.find((b) => b.partyIndex === 3)?.stats.maxHp)
.when("partyIndex", "=", 4)
.then(partyBeasts.find((b) => b.partyIndex === 4)?.stats.maxHp)
.when("partyIndex", "=", 5)
.then(partyBeasts.find((b) => b.partyIndex === 5)?.stats.maxHp)
.else(0)
.end(),
}))
.where("userId", "=", userId)
.where("id", "in", beastIds)
.execute();
}
export async function healParty(userId: string) {
// Array of the user's party
const partyBeasts = await getBeastParty(userId);
const beastIds = partyBeasts.map((beast) => beast.id);

await db
.updateTable("beast")
.set((eb) => ({
currentHp: eb
.case()
.when("partyIndex", "=", 0)
.then(partyBeasts.find((b) => b.partyIndex === 0)?.stats.maxHp)
.when("partyIndex", "=", 1)
.then(partyBeasts.find((b) => b.partyIndex === 1)?.stats.maxHp)
.when("partyIndex", "=", 2)
.then(partyBeasts.find((b) => b.partyIndex === 2)?.stats.maxHp)
.when("partyIndex", "=", 3)
.then(partyBeasts.find((b) => b.partyIndex === 3)?.stats.maxHp)
.when("partyIndex", "=", 4)
.then(partyBeasts.find((b) => b.partyIndex === 4)?.stats.maxHp)
.when("partyIndex", "=", 5)
.then(partyBeasts.find((b) => b.partyIndex === 5)?.stats.maxHp)
.else(0)
.end(),
}))
.where("userId", "=", userId)
.where("id", "in", beastIds)
.execute();
}
Solution:
```ts await db .updateTable("beast") .set((eb) => { let caseBuilder: any = eb.case();...
Jump to solution
3 Replies
Solution
yayza_
yayza_2mo ago
await db
.updateTable("beast")
.set((eb) => {
let caseBuilder: any = eb.case();

for (const beast of partyBeasts) {
caseBuilder = caseBuilder
.when("partyIndex", "=", beast.partyIndex)
.then(beast.stats.maxHp);
}

return {
currentHp: caseBuilder.else(0).end(),
};
})
.where("userId", "=", userId)
.where("id", "in", beastIds)
.execute();
await db
.updateTable("beast")
.set((eb) => {
let caseBuilder: any = eb.case();

for (const beast of partyBeasts) {
caseBuilder = caseBuilder
.when("partyIndex", "=", beast.partyIndex)
.then(beast.stats.maxHp);
}

return {
currentHp: caseBuilder.else(0).end(),
};
})
.where("userId", "=", userId)
.where("id", "in", beastIds)
.execute();
UV
UVOP2mo ago
Thanks that worked! so the any is necessary for it to work here?

Did you find this page helpful?