This repository has been archived on 2024-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
p61-project/domain/use-cases/RetrieveHabitsTracker.ts

69 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-03-16 00:36:44 +01:00
import { HabitHistory } from "../entities/HabitHistory"
import type { HabitsTrackerData } from "../entities/HabitsTracker"
2024-03-15 22:48:28 +01:00
import { HabitsTracker } from "../entities/HabitsTracker"
import type { User } from "../entities/User"
2024-03-16 00:36:44 +01:00
import type { GetHabitProgressHistoryRepository } from "../repositories/GetHabitProgressHistory"
2024-03-15 22:48:28 +01:00
import type { GetHabitsByUserIdRepository } from "../repositories/GetHabitsByUserId"
export interface RetrieveHabitsTrackerUseCaseDependencyOptions {
getHabitsByUserIdRepository: GetHabitsByUserIdRepository
2024-03-16 00:36:44 +01:00
getHabitProgressHistoryRepository: GetHabitProgressHistoryRepository
2024-03-15 22:48:28 +01:00
}
export interface RetrieveHabitsTrackerUseCaseOptions {
userId: User["id"]
}
export class RetrieveHabitsTrackerUseCase
implements RetrieveHabitsTrackerUseCaseDependencyOptions
{
public getHabitsByUserIdRepository: GetHabitsByUserIdRepository
2024-03-16 00:36:44 +01:00
public getHabitProgressHistoryRepository: GetHabitProgressHistoryRepository
2024-03-15 22:48:28 +01:00
public constructor(options: RetrieveHabitsTrackerUseCaseDependencyOptions) {
this.getHabitsByUserIdRepository = options.getHabitsByUserIdRepository
2024-03-16 00:36:44 +01:00
this.getHabitProgressHistoryRepository =
options.getHabitProgressHistoryRepository
2024-03-15 22:48:28 +01:00
}
public async execute(
options: RetrieveHabitsTrackerUseCaseOptions,
): Promise<HabitsTracker> {
const { userId } = options
const habits = await this.getHabitsByUserIdRepository.execute({ userId })
const habitProgressHistories = await Promise.all(
habits.map(async (habit) => {
2024-03-16 00:36:44 +01:00
const progressHistory =
await this.getHabitProgressHistoryRepository.execute({
2024-03-15 22:48:28 +01:00
habit,
2024-03-16 00:36:44 +01:00
})
2024-03-22 10:23:28 +01:00
return new HabitHistory({
habit,
progressHistory: progressHistory.sort((a, b) => {
return a.date.getTime() - b.date.getTime()
}),
})
2024-03-15 22:48:28 +01:00
}),
)
const habitsHistory = habitProgressHistories.reduce<
HabitsTrackerData["habitsHistory"]
>(
(accumulator, habitHistory) => {
const { habit } = habitHistory
const frequency = habit.goal.frequency
accumulator[frequency].push(habitHistory)
return accumulator
},
{
daily: [],
weekly: [],
monthly: [],
},
)
2024-03-16 00:36:44 +01:00
const habitsTracker = new HabitsTracker({
habitsHistory,
2024-03-16 00:36:44 +01:00
})
2024-03-15 22:48:28 +01:00
return habitsTracker
}
}