Skip to content

Commit

Permalink
toggle fav and test from backend b00tc4mp#407
Browse files Browse the repository at this point in the history
  • Loading branch information
berlem committed Apr 20, 2024
1 parent dbf1be2 commit 295c7c3
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
49 changes: 49 additions & 0 deletions staff/belen-ivars/project/api/logic/toggleFavRecipe.js
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 staff/belen-ivars/project/api/logic/toggleFavRecipe.test.js
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)
}
})()

0 comments on commit 295c7c3

Please sign in to comment.