Skip to content

Commit

Permalink
implement toggle fav api and app b00tc4mp#407
Browse files Browse the repository at this point in the history
  • Loading branch information
berlem committed Apr 20, 2024
1 parent 295c7c3 commit 8c0b730
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 9 deletions.
4 changes: 3 additions & 1 deletion staff/belen-ivars/project/api/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import createRecipeHandler from './createRecipeHandler.js'
import retrieveRecipesHandler from './retrieveRecipesHandler.js'
import deleteRecipeHandler from './deleteRecipeHandler.js'
import editRecipeHandler from './editeRecipeHandler.js'
import toggleFavRecipeHandler from './toggleFavRecipeHandler.js'


export {
Expand All @@ -14,5 +15,6 @@ export {
createRecipeHandler,
retrieveRecipesHandler,
deleteRecipeHandler,
editRecipeHandler
editRecipeHandler,
toggleFavRecipeHandler
}
32 changes: 32 additions & 0 deletions staff/belen-ivars/project/api/handlers/toggleFavRecipeHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import logic from "../logic/index.js"
import jwt from 'jsonwebtoken'
import { errors } from 'com'
const { NotFoundError, ContentError } = errors


const toggleFavRecipeHandler = async (req, res) => {

const token = req.headers.authorization.substring(7)

const { sub: userId } = jwt.verify(token, process.env.JWT_SECRET)

const recipeId = req.params.recipeId

try {
await logic.toggleFavRecipe(userId, recipeId)

res.status(204).send()

} catch (error) {
let status = 500

if (error instanceof NotFoundError)
status = 404
if (error instanceof ContentError || error instanceof TypeError)
status = 500
res.status(status).json({ error: error.constructor.name, message: error.message })
}

}

export default toggleFavRecipeHandler
5 changes: 4 additions & 1 deletion staff/belen-ivars/project/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
createRecipeHandler,
retrieveRecipesHandler,
deleteRecipeHandler,
editRecipeHandler
editRecipeHandler,
toggleFavRecipeHandler

} from './handlers/index.js'

Expand Down Expand Up @@ -40,6 +41,8 @@ mongoose.connect(process.env.MONGODB_URL)

server.patch('/recipes/:recipeId', jsonBodyParser, editRecipeHandler)

server.patch('/users/:recipeId', toggleFavRecipeHandler)

server.listen(process.env.PORT, () => console.log(`server running on port ${process.env.PORT}`))
})

Expand Down
4 changes: 3 additions & 1 deletion staff/belen-ivars/project/api/logic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import createRecipe from './createRecipe.js'
import retrieveRecipes from './retrieveRecipes.js'
import deleteRecipe from './deleteRecipe.js'
import editRecipe from './editRecipe.js'
import toggleFavRecipe from './toggleFavRecipe.js'

const logic = {
registerUser,
Expand All @@ -13,7 +14,8 @@ const logic = {
createRecipe,
retrieveRecipes,
deleteRecipe,
editRecipe
editRecipe,
toggleFavRecipe
}

export default logic
7 changes: 5 additions & 2 deletions staff/belen-ivars/project/api/logic/toggleFavRecipe.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { validate } from 'com'
import { User, Recipe } from '../data/models.js'
import { SystemError } from 'com/errors.js'
import { NotFoundError } from 'com/errors.js'

async function toggleFavPost(userId, recipeId) {
async function toggleFavRecipe(userId, recipeId) {
validate.id(userId, 'user id')
validate.id(recipeId, 'user id')

let user

try {
user = await User.findById(userId)
console.log('user founded')
} catch (error) {
throw new SystemError(error.message)
}
Expand All @@ -21,6 +23,7 @@ async function toggleFavPost(userId, recipeId) {

try {
recipe = await Recipe.findById(recipeId)
console.log('recipe founded')
} catch (error) {
throw new SystemError(error.message)
}
Expand All @@ -46,4 +49,4 @@ async function toggleFavPost(userId, recipeId) {
}
}

export default toggleFavPost
export default toggleFavRecipe
51 changes: 51 additions & 0 deletions staff/belen-ivars/project/api/test/toggle-fav-recipe.test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
source pepetest.sh

TEST 'toggle-fav-recipe'

CASE 'success on current user'

curl 'http://localhost:9000/users/66229b4f6c6c99938fab1a5b' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NWQ2NDJlOTY5NWNlMDFiNTM1ODVhODUiLCJpYXQiOjE3MTM2Mjg2NjgsImV4cCI6MTcxMzYzMjI2OH0.dJe5OIV7Un3fU6wcBTA2uhRhxAr0AmdPq8k_37X458w' \
-v

# > POST /recipes HTTP/1.1
# > Host: localhost:9000
# > User-Agent: curl/8.4.0
# > Accept: */*
# > Content-Type: application/json
# > Content-Length: 187
# >
# < HTTP/1.1 201 Created
# < X-Powered-By: Express
# < Access-Control-Allow-Origin: *
# < Date: Thu, 21 Mar 2024 17:45:59 GMT
# < Connection: keep-alive
# < Keep-Alive: timeout=5
# < Content-Length: 0

# CASE "fail on non existing user"

# curl 'http://localhost:9000/recipes' \
# -H 'Content-Type: application/json' \
# -d '{"author": "65d655fac1dd88f9aee917d7", "title": "Colors", "description": "Persona con pintura corporal", "image":"https://www.pexels.com/es-es/foto/persona-con-pintura-corporal-1209843/"}' \
# -v

# > POST /recipes HTTP/1.1
# > Host: localhost:9000
# > User-Agent: curl/8.4.0
# > Accept: */*
# > Content-Type: application/json
# > Content-Length: 187
# >
# < HTTP/1.1 404 Not Found
# < X-Powered-By: Express
# < Access-Control-Allow-Origin: *
# < Content-Type: application/json; charset=utf-8
# < Content-Length: 52
# < ETag: W/"34-Cs2INrsYwSHLSHCKVUFPEWh9NjI"
# < Date: Thu, 21 Mar 2024 17:45:59 GMT
# < Connection: keep-alive
# < Keep-Alive: timeout=5
# <
# * Connection #0 to host localhost left intact
# {"error":"NotFoundError","message":"user not found"}%
18 changes: 16 additions & 2 deletions staff/belen-ivars/project/app/src/components/Recipe.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function Recipe(props) {
document.getElementById("edit-form").reset()

} catch (error) {
console.log(error)
context.handleError(error)
}
}

Expand All @@ -43,7 +43,19 @@ function Recipe(props) {
props.onSuccess()

} catch (error) {
console.log(error)
context.handleError(error)
}
}

const handleToggleFavClick = async (event) => {
event.preventDefault
try {
await logic.toggleFavRecipe(props.recipe._id)
props.onSuccess()
console.log('fav done')

} catch (error) {
context.handleError(error)
}
}

Expand All @@ -63,6 +75,8 @@ function Recipe(props) {
<div>
{session.sessionUserId === props.recipe.author && view === null && <Button onClick={handleDeleteClick}>🗑️</Button>}
{session.sessionUserId === props.recipe.author && view === null && <Button className="edit-recipe" onClick={() => setView('edit')}>Edit</Button>}
<Button onClick={handleToggleFavClick}>{props.recipe.fav ? '❤️' : '🤍'}</Button>

</div>

{view === 'edit' && <Button onClick={() => setView(null)}>Cancel</Button>}
Expand Down
4 changes: 3 additions & 1 deletion staff/belen-ivars/project/app/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@
}

.recipes {
@apply flex flex-col items-center mb-[3rem] md:grid md:grid-cols-2 lg:grid-cols-3 bg-gradient-to-r from-zinc-400/50 to-rose-700/50;
@apply flex flex-col items-center mb-[3rem] md:grid md:grid-cols-2 lg:grid-cols-3;
/* bg-gradient-to-r from-zinc-400/50 to-rose-700/50; */
background:url(https://www.comedera.com/wp-content/uploads/2014/03/arroz-tres-delicias.jpg);
}

.search {
Expand Down
4 changes: 3 additions & 1 deletion staff/belen-ivars/project/app/src/logic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import createRecipe from './createRecipe'
import retrieveRecipes from './retrieveRecipes'
import editRecipe from './editRecipe'
import deleteRecipe from './deleteRecipe'
import toggleFavRecipe from './toggleFavRecipe'

const logic = {
registerUser,
Expand All @@ -17,7 +18,8 @@ const logic = {
createRecipe,
retrieveRecipes,
editRecipe,
deleteRecipe
deleteRecipe,
toggleFavRecipe
}

export default logic
36 changes: 36 additions & 0 deletions staff/belen-ivars/project/app/src/logic/toggleFavRecipe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { API_URL } from "../utils/constants"
import { errors } from 'com'
import session from "./session"

const { SystemError } = errors

export default function toggleFavRecipe(recipeId) {
return (async () => {
const req = {
method: 'PATCH',
headers: {
Authorization: `Bearer ${session.token}`
}
}

let res

try {
res = await fetch(`${API_URL}/users/${recipeId}`, req)
} catch (error) {
throw new SystemError(error.message)
}

if (!res.ok) {
let body

try {
body = await res.json()
} catch (error) {
throw new SystemError(errors.message)
}
throw new errors[body.error](body.message)
}

})()
}

0 comments on commit 8c0b730

Please sign in to comment.