forked from pinks/eris
1
0
Fork 0
eris/app/globalStats.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-10-09 19:03:31 +00:00
import { addDays } from "date-fns";
import { JsonSchema, jsonType } from "t_rest/server";
import { decodeTime } from "ulid";
import { getDailyStats } from "./dailyStatsStore.ts";
import { generationStore } from "./generationStore.ts";
export const globalStatsSchema = {
type: "object",
properties: {
userIds: { type: "array", items: { type: "number" } },
imageCount: { type: "number" },
2023-10-13 11:47:57 +00:00
stepCount: { type: "number" },
2023-10-09 19:03:31 +00:00
pixelCount: { type: "number" },
2023-10-13 11:47:57 +00:00
pixelStepCount: { type: "number" },
2023-10-09 19:03:31 +00:00
timestamp: { type: "number" },
},
2023-10-13 11:47:57 +00:00
required: ["userIds", "imageCount", "stepCount", "pixelCount", "pixelStepCount", "timestamp"],
2023-10-09 19:03:31 +00:00
} as const satisfies JsonSchema;
export type GlobalStats = jsonType<typeof globalStatsSchema>;
2023-10-13 11:47:57 +00:00
export const globalStats: GlobalStats = await getGlobalStats();
2023-10-09 19:03:31 +00:00
2023-10-13 11:47:57 +00:00
async function getGlobalStats(): Promise<GlobalStats> {
2023-10-09 19:03:31 +00:00
// find the year/month/day of the first generation
const startDate = await generationStore.getAll({}, { limit: 1 })
.then((generations) => generations[0]?.id)
.then((generationId) => generationId ? new Date(decodeTime(generationId)) : new Date());
// iterate to today and sum up stats
const userIdSet = new Set<number>();
let imageCount = 0;
2023-10-13 11:47:57 +00:00
let stepCount = 0;
2023-10-09 19:03:31 +00:00
let pixelCount = 0;
2023-10-13 11:47:57 +00:00
let pixelStepCount = 0;
2023-10-09 19:03:31 +00:00
const tomorrow = addDays(new Date(), 1);
for (
let date = startDate;
date < tomorrow;
date = addDays(date, 1)
) {
const dailyStats = await getDailyStats(
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
);
for (const userId of dailyStats.userIds) userIdSet.add(userId);
imageCount += dailyStats.imageCount;
2023-10-13 11:47:57 +00:00
stepCount += dailyStats.stepCount;
2023-10-09 19:03:31 +00:00
pixelCount += dailyStats.pixelCount;
2023-10-13 11:47:57 +00:00
pixelStepCount += dailyStats.pixelStepCount;
2023-10-09 19:03:31 +00:00
}
return {
userIds: [...userIdSet],
imageCount,
2023-10-13 11:47:57 +00:00
stepCount,
2023-10-09 19:03:31 +00:00
pixelCount,
2023-10-13 11:47:57 +00:00
pixelStepCount,
2023-10-09 19:03:31 +00:00
timestamp: Date.now(),
};
}