Skip to content

Commit f586aff

Browse files
Refactor visitor badge logic to use database for view count and improve user tracking
1 parent b7fdf07 commit f586aff

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/index.ts

+25-15
Original file line numberDiff line numberDiff line change
@@ -727,22 +727,35 @@ app.get("/visitor-badge/:repo", async (c) => {
727727
const repo = c.req.param("repo");
728728
const username = repo.split("/")[0];
729729
const isGitHub = isGitHubRequest(c.req.raw);
730-
const redis = Redis.fromEnv(c.env);
731730

732-
const viewKey = `views:${repo}`;
733-
let count = parseInt((await redis.get(viewKey)) || "0");
731+
let result = await c.env.DB.prepare(
732+
"SELECT count FROM visitors WHERE repo = ?"
733+
)
734+
.bind(repo)
735+
.first();
736+
737+
let count: number = typeof result?.count === "number" ? result.count : 0;
734738

735739
if (isGitHub) {
736740
c.executionCtx.waitUntil(
737741
(async () => {
738-
const [userResult] = await Promise.all([
739-
c.env.DB.prepare(
740-
`SELECT * FROM github_users WHERE username = ?1 AND (julianday(CURRENT_TIMESTAMP) - julianday(last_updated)) * 24 < 24`
741-
)
742-
.bind(username)
743-
.first(),
744-
redis.incr(viewKey),
745-
]);
742+
await c.env.DB.prepare(
743+
`INSERT INTO visitors (repo, count, last_updated)
744+
VALUES (?1, 1, CURRENT_TIMESTAMP)
745+
ON CONFLICT(repo) DO UPDATE SET
746+
count = count + 1,
747+
last_updated = CURRENT_TIMESTAMP`
748+
)
749+
.bind(repo)
750+
.run();
751+
752+
const userResult = await c.env.DB.prepare(
753+
`SELECT * FROM github_users
754+
WHERE username = ?1
755+
AND (julianday(CURRENT_TIMESTAMP) - julianday(last_updated)) * 24 < 24`
756+
)
757+
.bind(username)
758+
.first();
746759

747760
if (!userResult) {
748761
const githubUser = await getGitHubUser(username);
@@ -759,11 +772,8 @@ app.get("/visitor-badge/:repo", async (c) => {
759772
}
760773
})()
761774
);
762-
}
763775

764-
if (!count && isGitHub) {
765-
count = 1;
766-
await redis.set(viewKey, count);
776+
count++;
767777
}
768778

769779
const style = (c.req.query("style") as BadgeStyle["style"]) || "flat";

0 commit comments

Comments
 (0)