Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Commit

Permalink
Provide Goals
Browse files Browse the repository at this point in the history
  • Loading branch information
henrybrink committed Jun 14, 2024
1 parent ca4d7b0 commit 2b69497
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 0 deletions.
13 changes: 13 additions & 0 deletions backend/prisma/migrations/20240614204325_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "Goal" (
"userId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"source" TEXT NOT NULL,
"target" REAL NOT NULL,
"value" REAL NOT NULL,
"metric" TEXT NOT NULL,
"synced" DATETIME NOT NULL,

PRIMARY KEY ("userId", "type"),
CONSTRAINT "Goal_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
14 changes: 14 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ model User {
providers FitnessProviderCredential[]
notificationMethod String @default("EMAIL")
Points Points[]
Goal Goal[]
}

model FitnessProviderCredential {
Expand Down Expand Up @@ -53,3 +54,16 @@ model Points {
@@id([userId, day])
}

model Goal {
userId String
owner User @relation(fields: [userId], references: [id])
type String
source String
target Float
value Float
metric String
synced DateTime
@@id([userId, type])
}
2 changes: 2 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import configuration from './config/configuration';
import { NotificationModule } from './notification/notification.module';
import { TaskModule } from './app/tasks/task.module';
import { StreakModule } from './app/streaks/streak.module';
import { GoalModule } from './app/goals/goal.module';

@Module({
imports: [
Expand All @@ -23,6 +24,7 @@ import { StreakModule } from './app/streaks/streak.module';
NotificationModule,
TaskModule,
StreakModule,
GoalModule,
],
controllers: [AppController, UserController],
providers: [
Expand Down
43 changes: 43 additions & 0 deletions backend/src/app/goals/goal.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { NestRequest } from '../../types/request.type';
import { Response } from 'express';
import { FitnessDataNotAvailable, GoalService } from './goal.service';
import { AutoGuard } from '../../auth/auto.guard';
import { Goal } from '@prisma/client';

@Controller('/goal')
export class GoalController {
constructor(private goalService: GoalService) {}

private transformGoal(goal: Goal) {
return {
type: goal.type,
creator: goal.source,
target: goal.target,
value: goal.value,
metric: goal.metric,
};
}

@Get('/')
@UseGuards(AutoGuard)
public async get(@Req() request: NestRequest, @Res() response: Response) {
try {
const goals = await this.goalService.getGoalsForUser(request.user.id);

return response.status(200).json(goals.map((g) => this.transformGoal(g)));
} catch (e) {
if (e instanceof FitnessDataNotAvailable) {
return response
.status(400)
.json({ error: 'No Fitness Provider is available' });
}

if (e instanceof Error) {
console.log(e.stack);
}

return response.status(500).json({ error: 'Unknown error' });
}
}
}
12 changes: 12 additions & 0 deletions backend/src/app/goals/goal.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../../db/prisma.module';
import { GoalService } from './goal.service';
import { GoalController } from './goal.controller';
import FitnessModule from '../../integration/fitness/fitness.module';

@Module({
imports: [PrismaModule, FitnessModule],
providers: [GoalService],
controllers: [GoalController],
})
export class GoalModule {}
77 changes: 77 additions & 0 deletions backend/src/app/goals/goal.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Injectable } from '@nestjs/common';
import { GoalRepository } from '../../db/repositories/goal.repository';
import { Goal, Prisma } from '@prisma/client';
import * as dayjs from 'dayjs';
import { FitnessService } from '../../integration/fitness/fitness.service';

export class FitnessDataNotAvailable extends Error {}

@Injectable()
export class GoalService {
constructor(
private goalRepository: GoalRepository,
private fitnessService: FitnessService,
) {}

private atLeastOneGoalIsTooOld(goals: Goal[]): boolean {
for (const goal of goals) {
if (dayjs().subtract(1, 'hour').isAfter(goal.synced)) {
return true;
}
}

return false;
}

public async refreshGoals(userId, existing: Goal[]): Promise<Goal[]> {
const fitnessData = await this.fitnessService.getFitnessDataForUser(userId);

if (!fitnessData) {
throw new FitnessDataNotAvailable();
}

const goals: Goal[] = [];

for (const rawGoal of fitnessData.goals) {
if (!existing.find((g) => g.type == rawGoal.type)) {
const goal = await this.goalRepository.createGoal({
owner: { connect: { id: userId } },
type: rawGoal.type,
source: 'provider',
value: rawGoal.value,
target: rawGoal.goal,
metric: rawGoal.unit.toString(),
synced: new Date(),
} as Prisma.GoalCreateInput);

goals.push(goal);
} else {
const goal = await this.goalRepository.updateGoal(
userId,
rawGoal.type,
{
value: rawGoal.value,
target: rawGoal.goal,
metric: rawGoal.unit.toString(),
synced: new Date(),
} as Prisma.GoalCreateInput,
);

goals.push(goal);
}
}

return goals;
}

public async getGoalsForUser(userId): Promise<Goal[]> {
// Get goals from the database
const goals = await this.goalRepository.getGoals(userId);

if (goals.length < 1 || this.atLeastOneGoalIsTooOld(goals)) {
return await this.refreshGoals(userId, goals);
}

return goals;
}
}
3 changes: 3 additions & 0 deletions backend/src/db/prisma.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@ import { PrismaService } from './prisma.service';
import { FitnessRepository } from './repositories/fitness.repository';
import { TaskRepository } from './repositories/task.repository';
import { StreakRepository } from './repositories/streak.repository';
import { GoalRepository } from './repositories/goal.repository';
@Module({
providers: [
PrismaService,
UserRepository,
FitnessRepository,
StreakRepository,
TaskRepository,
GoalRepository,
],
exports: [
PrismaService,
UserRepository,
FitnessRepository,
StreakRepository,
TaskRepository,
GoalRepository,
],
})
export class PrismaModule {}
46 changes: 46 additions & 0 deletions backend/src/db/repositories/goal.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Goal, Prisma } from '@prisma/client';
import { PrismaService } from '../prisma.service';
import { Injectable } from '@nestjs/common';

@Injectable()
export class GoalRepository {
constructor(private client: PrismaService) {}

public async getGoals(userId: string): Promise<Goal[]> {
return await this.client.goal.findMany({
where: {
userId,
},
});
}

public async updateGoal(
userId: string,
type: string,
goal: Prisma.GoalUpdateInput,
): Promise<Goal> {
return await this.client.goal.update({
where: {
userId_type: {
userId,
type,
},
},
data: goal,
});
}

public async createGoal(goal: Prisma.GoalCreateInput): Promise<Goal> {
return await this.client.goal.create({
data: goal,
});
}

public async deleteGoalsForUser(userId): Promise<any> {
return await this.client.goal.deleteMany({
where: {
userId,
},
});
}
}

0 comments on commit 2b69497

Please sign in to comment.