forked from b00tc4mp/isdi-parttime-202309
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
toggle fav and test from backend b00tc4mp#407
- Loading branch information
Showing
2 changed files
with
65 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,49 @@ | ||
import { validate } from 'com' | ||
import { User, Recipe } from '../data/models.js' | ||
import { SystemError } from 'com/errors.js' | ||
|
||
async function toggleFavPost(userId, recipeId) { | ||
validate.id(userId, 'user id') | ||
validate.id(recipeId, 'user id') | ||
|
||
let user | ||
|
||
try { | ||
user = await User.findById(userId) | ||
} catch (error) { | ||
throw new SystemError(error.message) | ||
} | ||
|
||
if (!user) | ||
throw new NotFoundError('user not found') | ||
|
||
let recipe | ||
|
||
try { | ||
recipe = await Recipe.findById(recipeId) | ||
} catch (error) { | ||
throw new SystemError(error.message) | ||
} | ||
|
||
if (!recipe) | ||
throw new NotFoundError('recipe not found') | ||
|
||
const index = user.favs.findIndex(recipeObjectId => recipeObjectId.toString() === recipeId) | ||
|
||
if (index < 0) { | ||
try { | ||
await User.findOneAndUpdate({ _id: user.id }, { $push: { favs: recipeId } }) | ||
} catch (error) { | ||
throw new SystemError(error.message) | ||
} | ||
|
||
} else { | ||
try { | ||
await User.findOneAndUpdate({ _id: user.id }, { $pull: { favs: recipeId } }) | ||
} catch (error) { | ||
throw new SystemError(error.message) | ||
} | ||
} | ||
} | ||
|
||
export default toggleFavPost |
16 changes: 16 additions & 0 deletions
16
staff/belen-ivars/project/api/logic/toggleFavRecipe.test.js
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,16 @@ | ||
import dotenv from 'dotenv' | ||
dotenv.config() | ||
import mongoose from 'mongoose' | ||
|
||
import toggleFavPost from './toggleFavRecipe.js' | ||
|
||
(async () => { | ||
await mongoose.connect(process.env.MONGODB_URL) | ||
try { | ||
await toggleFavPost('65f85ac7883fd3713c8bd3a3', '66215a11f876a54941ba4cb1') | ||
|
||
console.log('favs has been done') | ||
} catch (error) { | ||
console.log(error) | ||
} | ||
})() |