MapleLeaf 🍁M
Convex Community3y ago
3 replies
MapleLeaf 🍁

Collection size limit

I have a collection of items that'll get created frequently, and I don't need to store them forever, so I want to delete old entries to preserve space.

My current strategy is to delete extra items once the collection size is over some arbitrary max.

I'm not that worried about performance since the collection isn't that big, nor is the limit, but I still wonder if there's a more performant/idiomatic way to accomplish this.

Here's my code:
const maxRolls = 250

export const roll = mutation({
    args: {
        type: v.optional(v.string()),
        label: v.optional(v.string()),
        characterId: v.optional(v.id("characters")),
        dice: v.array(v.object({ sides: v.number(), count: v.number() })),
    },
    handler: async (ctx, { dice, ...data }) => {
        const user = await requirePlayerUser(ctx)

        // make dice rolls
        const rolls = []
        for (const dieItem of dice) {
            for (let i = 0; i < dieItem.count; i++) {
                rolls.push({
                    sides: dieItem.sides,
                    result: Math.floor(Math.random() * dieItem.sides) + 1,
                })
            }
        }

        // add new dice roll
        await ctx.db.insert("diceRolls", {
            ...data,
            discordUserId: user.discordUserId,
            dice: rolls,
        })

        // remove old dice rolls if there are too many
        const allRolls = await ctx.db.query("diceRolls").collect()
        const excessRolls = allRolls.slice(0, -maxRolls)
        await Promise.all(excessRolls.map((r) => ctx.db.delete(r._id)))
    },
})
Was this page helpful?