Skip to content

Commit

Permalink
feat: ⚡ add fav route to add / remove fav
Browse files Browse the repository at this point in the history
  • Loading branch information
ae95caba committed Sep 16, 2024
1 parent 3598635 commit 4ca58ed
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 31 deletions.
10 changes: 3 additions & 7 deletions backend/src/album/album.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);
Expand All @@ -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
);
Expand All @@ -131,7 +127,7 @@ export class AlbumService {
data: updatedAlbum,
};
}
//albumFound.likes.push(userId);

const updatedAlbum = await this.albumModel.findByIdAndUpdate(
id, // Album ID
{
Expand All @@ -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!!!',
Expand Down
9 changes: 7 additions & 2 deletions backend/src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);
16 changes: 15 additions & 1 deletion backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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 = <mongoose.Types.ObjectId>user._id;
return await this.userService.favUnFav(userId, albumId);
}
}
42 changes: 41 additions & 1 deletion backend/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<User>,
@InjectModel(User.name) private readonly albumModel: mongoose.Model<Album>,
private userModel: mongoose.Model<User>,
) {}

async create(createUserDto: CreateUserDto): Promise<User> {
Expand Down Expand Up @@ -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,
};
}
}
40 changes: 20 additions & 20 deletions frontend/src/services/userServices.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}

0 comments on commit 4ca58ed

Please sign in to comment.