diff --git a/backend/src/album/album.service.ts b/backend/src/album/album.service.ts index 9bbac7f..1aeccf4 100644 --- a/backend/src/album/album.service.ts +++ b/backend/src/album/album.service.ts @@ -110,10 +110,6 @@ export class AlbumService { throw new NotFoundException(`Album with id ${id} not found`); } - /* if (albumFound.likes.includes(userId)) { - console.log('Hola!!!!'); - throw new ConflictException(`User ${userId} already likes this album`); - } */ const alreadyLiked = albumFound.likes.some((like) => like.userId.equals(userId), ); @@ -122,7 +118,7 @@ export class AlbumService { const updatedAlbum = await this.albumModel.findByIdAndUpdate( id, // Album ID { - $pull: { likes: { userId } }, // Add the userId to the likes array + $pull: { likes: { userId } }, // remove the userId from the likes array }, { new: true }, // Return the updated document ); @@ -131,7 +127,7 @@ export class AlbumService { data: updatedAlbum, }; } - //albumFound.likes.push(userId); + const updatedAlbum = await this.albumModel.findByIdAndUpdate( id, // Album ID { @@ -141,7 +137,7 @@ export class AlbumService { ); console.log(`album found is: ${JSON.stringify(albumFound)}`); - //await albumFound.save(); + return { message: 'Se ha dado like a esta porqueria que sigue siendo una porqueria!!!', diff --git a/backend/src/user/entities/user.entity.ts b/backend/src/user/entities/user.entity.ts index 887dc03..58f82ce 100644 --- a/backend/src/user/entities/user.entity.ts +++ b/backend/src/user/entities/user.entity.ts @@ -1,9 +1,9 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; - +import { Types, Document } from 'mongoose'; @Schema({ timestamps: true, }) -export class User { +export class User extends Document { @Prop({ unique: true, required: true, @@ -53,6 +53,11 @@ export class User { @Prop() imageUrl: string; + + @Prop({ + type: [{ type: Types.ObjectId, ref: 'Album' }], + }) + favs: Types.ObjectId[]; } export const UserSchema = SchemaFactory.createForClass(User); diff --git a/backend/src/user/user.controller.ts b/backend/src/user/user.controller.ts index 22046f6..02527db 100644 --- a/backend/src/user/user.controller.ts +++ b/backend/src/user/user.controller.ts @@ -13,7 +13,10 @@ import { UserService } from './user.service'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { User } from './entities/user.entity'; -import { ApiTags } from '@nestjs/swagger'; +import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { Auth, GetUser } from 'src/auth/decorators'; +import { ObjectIdValidationPipe } from 'src/common/pipes/object-id-validation.pipe'; +import mongoose, { Types } from 'mongoose'; @Controller('user') @ApiTags('Users') @@ -51,4 +54,15 @@ export class UserController { if (!user) throw new NotFoundException('User not found'); return; } + + @ApiBearerAuth() + @Post('fav/:id') + @Auth() + async favUnFav( + @GetUser() user: User, + @Param('id', ObjectIdValidationPipe) albumId: mongoose.Types.ObjectId, + ) { + const userId = user._id; + return await this.userService.favUnFav(userId, albumId); + } } diff --git a/backend/src/user/user.service.ts b/backend/src/user/user.service.ts index 8d6753a..e75d591 100644 --- a/backend/src/user/user.service.ts +++ b/backend/src/user/user.service.ts @@ -9,11 +9,13 @@ import { InjectModel } from '@nestjs/mongoose'; import mongoose from 'mongoose'; import { User } from './entities/user.entity'; import { HashAdapter } from 'src/common/adapters/hash.adapter'; +import { Album } from 'src/album/schemas'; @Injectable() export class UserService { constructor( - @InjectModel(User.name) private userModel: mongoose.Model, + @InjectModel(User.name) private readonly albumModel: mongoose.Model, + private userModel: mongoose.Model, ) {} async create(createUserDto: CreateUserDto): Promise { @@ -71,4 +73,42 @@ export class UserService { return userFound; } + + async favUnFav( + userId: mongoose.Types.ObjectId, + albumId: mongoose.Types.ObjectId, + ) { + console.log(`user id is : ${JSON.stringify(userId)}`); + const albumFound = await this.albumModel.findById(albumId); + if (!albumFound) { + throw new NotFoundException(`Album with id ${albumId} not found`); + } + + const user = await this.userModel.findById(userId); + const alreadyFav = user.favs.some((fav) => fav.equals(albumId)); + if (alreadyFav) { + //unfav + // Remove albumId from favs array using Mongoose's pull method + user.favs = user.favs.filter((fav) => !fav.equals(albumId)); + + // Save the updated user object + await user.save(); + return { + message: 'Se ha dado unfav a esta porqueria!!!', + data: user, + }; + } + + // Fav: Add albumId to favs + user.favs.push(albumId); + await user.save(); + + console.log(`album found is: ${JSON.stringify(albumFound)}`); + //await albumFound.save(); + return { + message: + 'Se ha dado fav a esta porqueria que sigue siendo una porqueria!!!', + data: user, + }; + } } diff --git a/frontend/src/services/userServices.ts b/frontend/src/services/userServices.ts index fc76746..d9aa004 100644 --- a/frontend/src/services/userServices.ts +++ b/frontend/src/services/userServices.ts @@ -1,49 +1,49 @@ -import { User, UserWithoutId } from '@/interfaces/user' +import { User, UserWithoutId } from "@/interfaces/user"; -const BASE_URL = process.env.API_URL +const BASE_URL = process.env.API_URL; //para actualizar solo los tags apenas se registra export async function patchUserService(id: string, userData: UserWithoutId) { - const url = BASE_URL + '/user/' + id + const url = BASE_URL + "/user/" + id; - console.log(url) + console.log(url); const response = await fetch(url, { - method: 'PATCH', + method: "PATCH", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ ...userData }), - cache: 'no-cache', - }) + cache: "no-cache", + }); if (!response.ok) { - throw new Error(`Error en la respuesta: ${response.status}`) + throw new Error(`Error en la respuesta: ${response.status}`); } - if (response.headers.get('Content-Type')?.includes('application/json')) { - const responseData = await response.json() - return responseData + if (response.headers.get("Content-Type")?.includes("application/json")) { + const responseData = await response.json(); + return responseData; } else { - throw new Error('La respuesta no es un JSON válido.') + throw new Error("La respuesta no es un JSON válido."); } } //para editar los datos del perfil con la mayoria de los datos export async function updateUserService(user: UserWithoutId, id: string) { - const url = BASE_URL + '/user/' + id + const url = BASE_URL + "/user/" + id; try { const response = await fetch(url, { - method: 'PATCH', + method: "PATCH", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ ...user }), - cache: 'no-cache', - }) + cache: "no-cache", + }); - return response.json() + return response.json(); } catch (error) { - console.error('Registration Service Error:', error) + console.error("Registration Service Error:", error); } }