Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: record visit per day #224

Merged
merged 9 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
getUserBySessionId,
getUsersByIds,
getVotedItemIdsByUser,
incrementVisitsPerDay,
type Item,
type User,
} from "@/utils/db.ts";
Expand Down Expand Up @@ -47,6 +48,7 @@ export const handler: Handlers<HomePageData, State> = {
votedItemIds = await getVotedItemIdsByUser(sessionUser!.id);
}
}
await incrementVisitsPerDay(new Date());
/** @todo Optimise */
const areVoted = items.map((item) => votedItemIds.includes(item.id));
return ctx.render({ ...ctx.state, items, cursor, users, areVoted });
Expand Down
20 changes: 20 additions & 0 deletions utils/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,23 @@ export async function getUsersByIds(ids: string[]) {
const res = await kv.getMany<User[]>(keys);
return res.map((entry) => entry.value!);
}

export async function incrementVisitsPerDay(date: Date) {
// convert to universal timezone (UTC)
const visitsKey = [
"visits",
`${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`,
];
await kv.atomic()
.sum(visitsKey, 1n)
.commit();
}

export async function getVisitsPerDay(date: Date) {
const res = await kv.get<bigint>([
"visits",
`${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`,
]);

return res.value;
}
14 changes: 14 additions & 0 deletions utils/db_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
getUserByLogin,
getUserBySessionId,
getUserByStripeCustomerId,
getVisitsPerDay,
incrementVisitsPerDay,
kv,
setUserSession,
setUserSubscription,
Expand Down Expand Up @@ -86,3 +88,15 @@ Deno.test("[db] user", async () => {
assertEquals(await getUserBySessionId(user.sessionId), null);
assertEquals(await getUserByStripeCustomerId(user.stripeCustomerId), null);
});

Deno.test("[db] visit", async () => {
const date = new Date("2023-01-01");
const visitsKey = [
"visits",
`${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`,
];
await incrementVisitsPerDay(date);
assertEquals((await getVisitsPerDay(date))!.valueOf(), 1n);
await kv.delete(visitsKey);
assertEquals(await getVisitsPerDay(date), null);
});