(
now?: Date,
options: { cache?: boolean } = {},
)
| 54 | } |
| 55 | |
| 56 | export async function getFreebuffLiveStats( |
| 57 | now?: Date, |
| 58 | options: { cache?: boolean } = {}, |
| 59 | ): Promise<FreebuffLiveStats> { |
| 60 | const useCache = options.cache ?? now === undefined |
| 61 | const requestTime = now ?? new Date() |
| 62 | |
| 63 | if (useCache && cachedLiveStats && cachedLiveStats.expiresAt > Date.now()) { |
| 64 | return cachedLiveStats.stats |
| 65 | } |
| 66 | |
| 67 | const [countryRows, modelRows] = await Promise.all([ |
| 68 | db |
| 69 | .select({ |
| 70 | countryCode: schema.freeSession.country_code, |
| 71 | count: count(), |
| 72 | }) |
| 73 | .from(schema.freeSession) |
| 74 | .where(liveSessionWhere(requestTime)) |
| 75 | .groupBy(schema.freeSession.country_code), |
| 76 | db |
| 77 | .select({ |
| 78 | modelId: schema.freeSession.model, |
| 79 | count: count(), |
| 80 | }) |
| 81 | .from(schema.freeSession) |
| 82 | .where(liveSessionWhere(requestTime)) |
| 83 | .groupBy(schema.freeSession.model), |
| 84 | ]) |
| 85 | |
| 86 | const countries = sortCounts( |
| 87 | countryRows.map((row) => ({ |
| 88 | countryCode: row.countryCode ?? 'UNKNOWN', |
| 89 | count: Number(row.count), |
| 90 | })), |
| 91 | ) |
| 92 | |
| 93 | const models = sortCounts( |
| 94 | modelRows.map((row) => ({ |
| 95 | modelId: row.modelId, |
| 96 | displayName: modelDisplayName(row.modelId), |
| 97 | count: Number(row.count), |
| 98 | })), |
| 99 | ) |
| 100 | |
| 101 | const stats = { |
| 102 | totalLiveUsers: models.reduce((sum, row) => sum + row.count, 0), |
| 103 | countries, |
| 104 | models, |
| 105 | generatedAt: requestTime.toISOString(), |
| 106 | } |
| 107 | |
| 108 | if (useCache) { |
| 109 | cachedLiveStats = { |
| 110 | expiresAt: Date.now() + LIVE_STATS_CACHE_MS, |
| 111 | stats, |
| 112 | } |
| 113 | } |
no test coverage detected