Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
pauloendoh committed Oct 20, 2024
1 parent 2388c44 commit 2fa274d
Show file tree
Hide file tree
Showing 27 changed files with 204 additions and 285 deletions.
14 changes: 7 additions & 7 deletions src/domains/auth/AuthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { PasswordResetPostDto } from "../../interfaces/dtos/auth/PasswordResetPo
import { UserDeleteDto } from "../../interfaces/dtos/auth/UserDeleteDto"
import { UserTokenPostDto } from "../../interfaces/dtos/auth/UserTokenPostDto"
import { UsernamePutDto } from "../../interfaces/dtos/auth/UsernamePutDto"
import UserRepository from "../../repositories/UserRepository"
import { UserRepository } from "../../repositories/UserRepository"
import { MyAuthRequest } from "../../utils/MyAuthRequest"
import { $SaveUser } from "../user/use-cases/$SaveUser"
import { AuthService } from "./AuthService"
Expand All @@ -33,10 +33,10 @@ import { RegisterDto } from "./types/RegisterDto"
@JsonController("/auth")
export class AuthController {
constructor(
private userRepo = UserRepository,
private preferenceRepo = dataSource.getRepository(UserPreference),
private authService = new AuthService(),
private $saveUser = new $SaveUser()
private readonly userRepo = new UserRepository(),
private readonly preferenceRepo = dataSource.getRepository(UserPreference),
private readonly authService = new AuthService(),
private readonly $saveUser = new $SaveUser()
) {}

@Post("/register")
Expand Down Expand Up @@ -122,7 +122,7 @@ export class AuthController {

if (!passwordOk) throw new BadRequestError("Incorrect password.")
if (passwordOk) {
await this.userRepo.delete({ id: requester.id })
await this.userRepo.rawRepo.delete({ id: requester.id })

return true
}
Expand All @@ -135,7 +135,7 @@ export class AuthController {
) {
const { newUsername } = body

const usernameExists = await this.userRepo.findOne({
const usernameExists = await this.userRepo.rawRepo.findOne({
where: {
username: newUsername,
},
Expand Down
28 changes: 14 additions & 14 deletions src/domains/auth/AuthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { User } from "../../entities/User"
import { AuthUserGetDto } from "../../interfaces/dtos/auth/AuthUserGetDto"
import { PasswordResetPostDto } from "../../interfaces/dtos/auth/PasswordResetPostDto"
import { UserTokenPostDto } from "../../interfaces/dtos/auth/UserTokenPostDto"
import UserRepository from "../../repositories/UserRepository"
import { UserRepository } from "../../repositories/UserRepository"
import { myEnvs } from "../../utils/myEnvs"
import { addMinutes } from "../../utils/time/addMinutes"
import validateUserFields from "../../utils/validateUser"
Expand All @@ -22,14 +22,14 @@ import { RegisterDto } from "./types/RegisterDto"

export class AuthService {
constructor(
private userRepo = UserRepository,
private tokenRepo = dataSource.getRepository(UserToken),
private $saveUser = new $SaveUser()
private readonly userRepo = new UserRepository(),
private readonly tokenRepo = dataSource.getRepository(UserToken),
private readonly $saveUser = new $SaveUser()
) {}

async register(dto: RegisterDto) {
// only creates an instance. Doesn't save on DB
const sentUser = this.userRepo.create(dto)
const sentUser = this.userRepo.rawRepo.create(dto)
const userErrors = validateUserFields(sentUser)
if (userErrors.length) {
throw new BadRequestError(userErrors[0].message)
Expand All @@ -39,7 +39,7 @@ export class AuthService {
throw new BadRequestError("Passwords are different!")

// Checking if email exists
let userExists = await this.userRepo.findOne({
let userExists = await this.userRepo.rawRepo.findOne({
where: {
email: sentUser.email,
},
Expand All @@ -50,7 +50,7 @@ export class AuthService {
}

// Checking if username exists
userExists = await this.userRepo.findOne({
userExists = await this.userRepo.rawRepo.findOne({
where: {
username: sentUser.username,
},
Expand Down Expand Up @@ -102,7 +102,7 @@ export class AuthService {
}

// username or email exists ?
const user = await this.userRepo.findOne({
const user = await this.userRepo.rawRepo.findOne({
where: [{ email: sentUser.email }, { username: sentUser.email }],
})
if (!user) {
Expand Down Expand Up @@ -137,13 +137,13 @@ export class AuthService {
}

async keepTempUser(dto: RegisterDto, userId: number) {
const previousTempUser = await this.userRepo.findOne({
const previousTempUser = await this.userRepo.rawRepo.findOne({
where: { id: userId },
})
if (!previousTempUser) throw new BadRequestError("User not found")

// only creates an instance. Doesn't save on DB
const sentUser = this.userRepo.create(dto)
const sentUser = this.userRepo.rawRepo.create(dto)
const userErrors = validateUserFields(sentUser)
if (userErrors.length) {
throw new BadRequestError(userErrors[0].message)
Expand All @@ -153,7 +153,7 @@ export class AuthService {
throw new BadRequestError("Passwords are different!")

// Checking if email exists
let userExists = await this.userRepo.findOne({
let userExists = await this.userRepo.rawRepo.findOne({
where: {
email: sentUser.email,
},
Expand All @@ -164,7 +164,7 @@ export class AuthService {
}

// Checking if username exists
userExists = await this.userRepo.findOne({
userExists = await this.userRepo.rawRepo.findOne({
where: {
username: sentUser.username,
},
Expand Down Expand Up @@ -246,7 +246,7 @@ export class AuthService {

// Same process as POST /auth/login

const user = await this.userRepo.findOne({
const user = await this.userRepo.rawRepo.findOne({
where: {
id: userId,
},
Expand Down Expand Up @@ -295,7 +295,7 @@ export class AuthService {
if (!tokenExists)
throw new BadRequestError("Token does not exist or it is expired.")

const user = await this.userRepo.findOne({
const user = await this.userRepo.rawRepo.findOne({
where: {
id: userId,
},
Expand Down
1 change: 0 additions & 1 deletion src/domains/feed/follow/FollowRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export class FollowRepository {
}

async findFolloweesByFollowerId(followerId: number) {
// PE 1/3 - todo: don't return all fields
const follows = await this.db.getRepository(Follow).find({
where: {
followerId,
Expand Down
8 changes: 4 additions & 4 deletions src/domains/feed/follow/FollowService.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import UserRepository from "../../../repositories/UserRepository"
import { UserRepository } from "../../../repositories/UserRepository"
import { NotificationService } from "../../notification/NotificationService"
import { FollowRepository } from "./FollowRepository"

export class FollowService {
constructor(
private followRepo = new FollowRepository(),
private userRepo = UserRepository, // private notificationService = new NotificationService()
private notificationService = new NotificationService()
private readonly followRepo = new FollowRepository(),
private readonly userRepo = new UserRepository(),
private readonly notificationService = new NotificationService()
) {}

async toggleFollow(requesterId: number, followingUserId: number) {
Expand Down
18 changes: 0 additions & 18 deletions src/domains/monerate/category/CategoryController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import {
BadRequestError,
Body,
CurrentUser,
Delete,
Get,
JsonController,
Param,
Post,
} from "routing-controllers"
import { User } from "../../../entities/User"
Expand Down Expand Up @@ -47,20 +45,4 @@ export class CategoryController {
async getCategories(@CurrentUser({ required: true }) user: User) {
return this.categoryRepo.getCategoriesFromUser(user)
}

// PE 1/3 - not being used?
@Delete("/:id")
async deleteCategory(
@CurrentUser({ required: true }) user: User,
@Param("id") categoryId: number
) {
const result = await this.categoryRepo.delete({
id: categoryId,
userId: user.id,
})
if (!result.affected)
throw new BadRequestError("Category id not found, or user is not owner.")

return this.categoryRepo.getCategoriesFromUser(user)
}
}
6 changes: 3 additions & 3 deletions src/domains/notification/NotificationService.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NotFoundError } from "routing-controllers"
import { Follow } from "../../entities/feed/Follow"
import { UserRepositoryV2 } from "../user/UserRepositoryV2"
import { UserRepository } from "../../repositories/UserRepository"
import { NotificationRepositoryV2 } from "./NotificationRepositoryV2"

export class NotificationService {
constructor(
private userRepo = new UserRepositoryV2(),
private notificationRepo = new NotificationRepositoryV2()
private readonly userRepo = new UserRepository(),
private readonly notificationRepo = new NotificationRepositoryV2()
) {}

async createFollowNotification(follow: Follow) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ export class _SaveResource {
returnAll?: boolean
}) {
const { sentResource, user, returnAll = true } = params
if (sentResource.tag === null)
if (sentResource.tag === null) {
throw new BadRequestError("Resource must have a tag.")
}

if (sentResource.thumbnail === null) sentResource.thumbnail = ""

Expand All @@ -38,22 +39,18 @@ export class _SaveResource {
if (
previousResource.rating !== sentResource.rating &&
sentResource.rating > 0
)
) {
sentResource.completedAt = new Date().toISOString()
}

// PE 1/3 - Maybe it would be better to create a specific route for that...
// If adding a rating
if (!previousResource.rating && sentResource.rating > 0) {
await this.resourceRepo.reducePosition(
sentResource.tag,
await this.resourceRepo.decrementResourcePositionsInTag({
tag: sentResource.tag,
user,
sentResource.position + 1
)
startingPosition: sentResource.position + 1,
})

sentResource.completedAt = new Date().toISOString()
// sentResource.position = null

// TODO: reduce by 1 the others' positions
}
// If removing a rating
else if (previousResource.rating > 0 && sentResource.rating === null) {
Expand All @@ -70,11 +67,11 @@ export class _SaveResource {
previousResource.tag?.id != sentResource.tag?.id) && // changing tag
previousResource.position
) {
await this.resourceRepo.reducePosition(
previousResource.tag,
await this.resourceRepo.decrementResourcePositionsInTag({
tag: previousResource.tag,
user,
previousResource.position + 1
)
startingPosition: previousResource.position + 1,
})

sentResource.position = await this.resourceRepo.getLastPosition(
sentResource.tag,
Expand Down
37 changes: 0 additions & 37 deletions src/domains/skillbase/learning/ProgressController.ts

This file was deleted.

38 changes: 7 additions & 31 deletions src/domains/skillbase/skill/SkillController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import {
Body,
CurrentUser,
Delete,
ForbiddenError,
Get,
JsonController,
NotFoundError,
Param,
Post,
Put,
UseBefore,
} from "routing-controllers"
import { dataSource } from "../../../dataSource"
Expand All @@ -23,9 +20,13 @@ import SkillRepository from "../../../repositories/skillbase/SkillRepository"
@JsonController()
export class SkillController {
constructor(
private skillRepo = SkillRepository,
private skillProgressRepo = dataSource.getRepository(SkillProgress),
private skillExpectationRepo = dataSource.getRepository(SkillExpectation)
private readonly skillRepo = SkillRepository,
private readonly skillProgressRepo = dataSource.getRepository(
SkillProgress
),
private readonly skillExpectationRepo = dataSource.getRepository(
SkillExpectation
)
) {}

@Get("/skillbase/skill")
Expand Down Expand Up @@ -88,31 +89,6 @@ export class SkillController {
return savedSkill
}

@Put("/skillbase/skill/:id")
async updateSkill(
@UseBefore(MyAuthMiddleware)
@CurrentUser({ required: true })
user: User,
@Body() sentSkill: Skill,
@Param("id") skillId: number
) {
const isOwner = await this.skillRepo.findOne({
where: {
userId: user.id,
id: skillId,
},
})
if (!isOwner)
throw new ForbiddenError("User is not owner or skill doesn't exist")

if (isOwner) {
sentSkill.id = skillId // PE 1/3 - why do we need this?

const savedSkill = await this.skillRepo.save(sentSkill)
return savedSkill
}
}

@Delete("/skillbase/skill")
async deleteSkill(
@UseBefore(MyAuthMiddleware)
Expand Down
Loading

0 comments on commit 2fa274d

Please sign in to comment.