Skip to content

Commit

Permalink
Add entries today to streak API
Browse files Browse the repository at this point in the history
  • Loading branch information
nkalupahana committed Jan 19, 2025
1 parent 3efd248 commit f532fd6
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions backend/src/streak.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ enum Danger {
NO_RECOVERY = 3
}

export const calculateStreak = async (req: UserRequest, res: Response) => {
interface StreakResponse {
streak: number;
danger: Danger;
entriesToday: number;
}

export const calculateStreak = async (req: UserRequest, res: Response<StreakResponse>) => {
const db = getDatabase();
const data = req.body;
const encryptionKey = await validateKeys(data.keys, db, req.user!.user_id);
Expand All @@ -33,7 +39,7 @@ export const calculateStreak = async (req: UserRequest, res: Response) => {
const logRef = db.ref(req.user!.user_id + "/logs").orderByKey();
let logs: AnyMap = await (await logRef.limitToLast(FETCH_LIMIT).get()).val();
if (!logs || Object.keys(logs).length === 0) {
res.send({ streak: 0, danger: Danger.NO_RECOVERY });
res.send({ streak: 0, danger: Danger.NO_RECOVERY, entriesToday: 0 });
return;
}

Expand All @@ -52,18 +58,23 @@ export const calculateStreak = async (req: UserRequest, res: Response) => {

// If the top log is not in the last two days, the streak is 0 and cannot be recovered
if (danger === Danger.NO_RECOVERY) {
res.send({ streak: 0, danger: Danger.NO_RECOVERY });
res.send({ streak: 0, danger: Danger.NO_RECOVERY, entriesToday: 0 });
return;
}

let streak = 1;
let entriesToday = 0;
let running = true;
while (running && Object.keys(logs).length > 0) {
// Same general logic as `calculateStreak` in the frontend
// (max change of one day to continue streak)
const logKeys = Object.keys(logs).reverse();
for (const key of logKeys) {
const log = JSON.parse(AES.decrypt(logs[key].data, encryptionKey).toString(aesutf8));
if (streak === 1 && today.day === log.day && today.month === log.month && today.year === log.year) {
++entriesToday;
}

if (top.day !== log.day || top.month !== log.month || top.year !== log.year) {
const logDT = DateTime.fromObject({ year: log.year, month: log.month, day: log.day });
if (logDT.toISODate() === top.minus({ days: 1 }).toISODate()) {
Expand All @@ -82,5 +93,5 @@ export const calculateStreak = async (req: UserRequest, res: Response) => {
}
}

res.send({ streak, danger });
res.send({ streak, danger, entriesToday });
};

0 comments on commit f532fd6

Please sign in to comment.