bug in favorite

This commit is contained in:
2026-02-14 10:06:59 +03:30
parent a2727862bf
commit 0ebe9b10f1
2 changed files with 18 additions and 22 deletions
@@ -38,7 +38,7 @@ export class FoodController {
@ApiHeader(API_HEADER_SLUG)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get a product by id' })
findPublicFoodById(@Param('id') productId: string, @UserId() userId?: string): Promise<any> {
findPublicFoodById(@Param('id') productId: string, @UserId() userId: string): Promise<any> {
const a = this.productService.findPublicById(productId, userId);
return a;
}
@@ -48,8 +48,8 @@ export class FoodController {
@ApiHeader(API_HEADER_SLUG)
@ApiBearerAuth()
@ApiOperation({ summary: 'toggle a product as favorite' })
@ApiParam({ name: 'productId', required: true })
setAsFavorute(@Param('productId') productId: string, @UserId() userId: string) {
@ApiParam({ name: 'id', required: true, description: 'Product ID' })
setAsFavorite(@Param('id') productId: string, @UserId() userId: string) {
return this.productService.toggleFavorite(userId, productId);
}
@@ -76,13 +76,13 @@ export class ProductService {
}
async findPublicById(productId: string, userId?: string): Promise<any> {
async findPublicById(productId: string, userId: string): Promise<any> {
const product = await this.findOrFail(productId)
let isFavorite = false;
if (userId) {
isFavorite = (await this.em.count(Favorite, { user: { id: userId }, product: { id: productId } })) > 0;
isFavorite = (await this.favoriteRepository.findOne({ user: { id: userId }, product: { id: productId } })) ? true : false;
}
return {
...product,
@@ -191,31 +191,27 @@ export class ProductService {
async toggleFavorite(userId: string, productId: string) {
const user = await this.em.findOne(User, userId);
const product = await this.em.findOne(Product, productId);
const favorite = await this.em.findOne(Favorite, { user, product });
if (!user) {
throw new NotFoundException('User not found');
}
if (!product) {
throw new NotFoundException(ProductMessage.NOT_FOUND);
}
const favorite = await this.favoriteRepository.findOne({
user: { id: userId },
product: { id: productId },
});
if (favorite) {
await this.em.removeAndFlush(favorite);
return { message: 'Favorite removed successfully' };
}
if (!user) {
throw new Error('User not found');
}
if (!product) {
throw new Error('Product not found');
}
const newFavorite = this.em.create(Favorite, {
user,
product,
});
const newFavorite = this.em.create(Favorite, { user, product });
await this.em.persistAndFlush(newFavorite);
return { message: 'Favorite added successfully' };
}
@@ -224,7 +220,7 @@ export class ProductService {
async getMyFavorites(userId: string, shopId: string) {
return this.favoriteRepository.find({
user: { id: userId },
// product: { shop: { id: shopId } }
product: { shop: { id: shopId } }
},
{ populate: ['product'] }
);