Skip to content

Commit 7b18870

Browse files
committed
Add rate limit to page view counter
1 parent 51ee9e0 commit 7b18870

2 files changed

Lines changed: 24 additions & 9 deletions

File tree

apps/api/src/plugins/cache.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ class Cache {
3838
async hasUniqueLaunch(mod: string, version: string, ip: string) {
3939
return this.cache.has(`unique_launch:${mod}:${version}:${ip}`);
4040
}
41+
42+
async setPageView(mod: string, source: string, ip: string) {
43+
return this.cache.set(`page_view:${mod}:${source}:${ip}`, 1, "10m");
44+
}
45+
46+
async hasPageView(mod: string, source: string, ip: string) {
47+
return this.cache.has(`page_view:${mod}:${source}:${ip}`);
48+
}
4149
}
4250

4351
export default async function (fastify: FastifyInstance) {

apps/api/src/routes/banners/routes.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { z } from "zod";
55

66
export const plugin: FastifyPluginAsyncZod = async fastify => {
77
const db = fastify.mongo.db!;
8+
const cache = fastify.cache;
89

910
fastify.get(
1011
"/:mod_id",
@@ -41,15 +42,21 @@ export const plugin: FastifyPluginAsyncZod = async fastify => {
4142
return `Banner ${mod_id} not found.`;
4243
}
4344

44-
await db.collection<PageViews>(Collections.PageViews).updateOne(
45-
{ mod_id },
46-
{
47-
$inc: {
48-
[`${source}.${dayjs().format("YYYY.M.D")}`]: 1
49-
}
50-
},
51-
{ upsert: true }
52-
);
45+
const hasPageView = await cache.hasPageView(mod_id, source, request.ip);
46+
47+
if (!hasPageView) {
48+
await db.collection<PageViews>(Collections.PageViews).updateOne(
49+
{ mod_id },
50+
{
51+
$inc: {
52+
[`${source}.${dayjs().format("YYYY.M.D")}`]: 1
53+
}
54+
},
55+
{ upsert: true }
56+
);
57+
58+
await cache.setPageView(mod_id, source, request.ip);
59+
}
5360

5461
reply.redirect(
5562
`https://blakesmods.com/img/banner/${mod_id}_title.png`,

0 commit comments

Comments
 (0)