This repository has been archived by the owner on Oct 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Provide Goals * Tests for Goals * fix: Unecessary import
- Loading branch information
1 parent
a33ad2c
commit efa2672
Showing
9 changed files
with
303 additions
and
0 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
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 | ||
); |
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
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,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' }); | ||
} | ||
} | ||
} |
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,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 {} |
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,93 @@ | ||
import { Test } from '@nestjs/testing'; | ||
import { GoalService } from './goal.service'; | ||
import { GoalRepository } from '../../db/repositories/goal.repository'; | ||
import { FitnessService } from '../../integration/fitness/fitness.service'; | ||
import { DeepMockProxy, mockDeep } from 'jest-mock-extended'; | ||
import { Goal } from '@prisma/client'; | ||
import { TestConstants } from '../../../test/lib/constants'; | ||
import * as dayjs from 'dayjs'; | ||
import { FitnessData } from '../../integration/fitness/fitness.data'; | ||
import { FitnessGoal } from '../../integration/fitness/fitness.goal'; | ||
|
||
describe('GoalService', () => { | ||
let goalService: GoalService; | ||
let goalRepository: DeepMockProxy<GoalRepository>; | ||
let fitnessService: DeepMockProxy<FitnessService>; | ||
|
||
beforeEach(async () => { | ||
const moduleRef = await Test.createTestingModule({ | ||
providers: [GoalService, GoalRepository, FitnessService], | ||
}) | ||
.overrideProvider(GoalRepository) | ||
.useValue(mockDeep<GoalRepository>()) | ||
.overrideProvider(FitnessService) | ||
.useValue(mockDeep<FitnessService>()) | ||
.compile(); | ||
|
||
goalService = moduleRef.get<GoalService>(GoalService); | ||
goalRepository = moduleRef.get(GoalRepository); | ||
fitnessService = moduleRef.get(FitnessService); | ||
}); | ||
|
||
describe('getGoalsForUser', () => { | ||
it('should return cached goals, if they are not too old', async () => { | ||
const goal = { | ||
userId: TestConstants.database.users.exampleUser.id, | ||
type: 'steps', | ||
target: 200, | ||
value: 100, | ||
metric: 'steps', | ||
synced: dayjs().subtract(10, 'minutes').toDate(), | ||
} as Goal; | ||
|
||
goalRepository.getGoals.mockResolvedValue([goal]); | ||
|
||
const goals = await goalService.getGoalsForUser( | ||
TestConstants.database.users.exampleUser.id, | ||
); | ||
|
||
expect(goals.length).toBe(1); | ||
expect(goals[0]).toStrictEqual(goal); | ||
}); | ||
|
||
it('should refresh goals if the old goals are to old', async () => { | ||
const goal = { | ||
userId: TestConstants.database.users.exampleUser.id, | ||
type: 'steps', | ||
target: 200, | ||
value: 100, | ||
metric: 'steps', | ||
synced: dayjs().subtract(2, 'hours').toDate(), | ||
} as Goal; | ||
|
||
goalRepository.getGoals.mockResolvedValue([goal]); | ||
|
||
fitnessService.getFitnessDataForUser.mockResolvedValue({ | ||
goals: [ | ||
{ | ||
type: 'steps', | ||
goal: 200, | ||
value: 100, | ||
unit: 1, | ||
} as FitnessGoal, | ||
], | ||
} as FitnessData); | ||
|
||
goalRepository.updateGoal.mockResolvedValue({ | ||
userId: TestConstants.database.users.exampleUser.id, | ||
type: 'steps', | ||
target: 200, | ||
value: 100, | ||
metric: 'steps', | ||
synced: dayjs().subtract(2, 'hours').toDate(), | ||
} as Goal); | ||
|
||
const goals = await goalService.getGoalsForUser( | ||
TestConstants.database.users.exampleUser.id, | ||
); | ||
|
||
expect(goals.length).toBe(1); | ||
expect(goals[0]).toStrictEqual(goal); | ||
}); | ||
}); | ||
}); |
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,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; | ||
} | ||
} |
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,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, | ||
}, | ||
}); | ||
} | ||
} |