| 86 | } |
| 87 | |
| 88 | export async function getCreatureTopPercentage(id: string) { |
| 89 | try { |
| 90 | const creature = await db.query.creatures.findFirst({ |
| 91 | where: (creatures, { eq }) => eq(creatures.id, id), |
| 92 | }); |
| 93 | |
| 94 | if (!creature) { |
| 95 | throw new Error("Creature not found"); |
| 96 | } |
| 97 | |
| 98 | const [{ count: totalCreaturesRaw }] = await db |
| 99 | .select({ count: count() }) |
| 100 | .from(creatures); |
| 101 | |
| 102 | const totalCreatures = Number(totalCreaturesRaw ?? 0); |
| 103 | if (totalCreatures === 0) return 0; |
| 104 | |
| 105 | const [{ count: betterCreaturesRaw }] = await db |
| 106 | .select({ count: count() }) |
| 107 | .from(creatures) |
| 108 | .where(gt(creatures.contributions, creature.contributions)); |
| 109 | |
| 110 | const betterCreatures = Number(betterCreaturesRaw ?? 0); |
| 111 | const rank = betterCreatures + 1; |
| 112 | |
| 113 | return Math.round((rank / totalCreatures) * 100); |
| 114 | } catch (error) { |
| 115 | console.error(error); |
| 116 | throw new Error("Failed to get creature top percentage"); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | export async function searchCreaturesByUsername(query: string) { |
| 121 | if (!query || query.length < 1) return []; |