-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Done without storing any personal information such as IP address. Uses Redis HyperLogLog to keep count. Daily count and total count. Signed-off-by: Brian Evans <ebrian101@gmail.com>
- Loading branch information
1 parent
fcf943c
commit 2dd6361
Showing
2 changed files
with
105 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import type { RedisClient } from "./getRedisClient" | ||
|
||
|
||
/** | ||
* Keeps usage statistics without ever storing the clients IP address. | ||
* Uses a HyperLogLog in redis to count items WITHOUT storing them. | ||
* Preserves privacy and allows basic statistic reporting. | ||
*/ | ||
export class VisitorCounterService { | ||
|
||
redisClient: RedisClient | ||
|
||
constructor(redisClient: RedisClient) { | ||
this.redisClient = redisClient | ||
} | ||
|
||
/** | ||
* Counts an IP address. | ||
*/ | ||
async count(ip: string) { | ||
const date = new Date().toISOString().slice(0, 10) | ||
await this.redisClient.pfAdd(`visitors-${date}`, ip) | ||
await this.redisClient.pfAdd(`visitors-total`, ip) | ||
} | ||
|
||
/** | ||
* Get the count for a specific day. | ||
* @param date - ISO date string of the day to retrieve. | ||
*/ | ||
async getCount(date?: string) { | ||
date ??= new Date().toISOString().slice(0, 10) | ||
return await this.redisClient.pfCount(`visitors-${date}`) | ||
} | ||
|
||
/** | ||
* Get the total number counted since records began (9 September 2023). | ||
*/ | ||
async getTotalCount() { | ||
return await this.redisClient.pfCount(`visitors-total`) | ||
} | ||
|
||
} |