Skip to content

Commit

Permalink
retrieve logic in app b00tc4mp#407
Browse files Browse the repository at this point in the history
  • Loading branch information
berlem committed Apr 16, 2024
1 parent 00fefde commit 26e3231
Show file tree
Hide file tree
Showing 12 changed files with 193 additions and 126 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ContentError, NotFoundError } from 'com/errors.js'
import logic from '../logic.index.js'
import logic from '../logic/index.js'
import { validate } from "com"


const retrieveRecipesHandler = async (req, res) => {
const userId = req.params.userId
const userId = req.params.id

try {
validate.id(userId, 'id')
Expand Down
2 changes: 1 addition & 1 deletion staff/belen-ivars/project/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ mongoose.connect(process.env.MONGODB_URL)

server.post('/recipes', jsonBodyParser, createRecipeHandler)

server.get('/recipes', retrieveRecipesHandler)
server.get('/recipes/:id', retrieveRecipesHandler)

server.listen(process.env.PORT, () => console.log(`server running on port ${process.env.PORT}`))
})
Expand Down
4 changes: 2 additions & 2 deletions staff/belen-ivars/project/api/logic/retrieveRecipes.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { NotFoundError } from "com/errors.js"
import { Recipe } from "../data/models.js"
import { Recipe, User } from "../data/models.js"
import retrieveUser from "./retrieveUser.js"

async function retrieveRecipes(id) {

const user = retrieveUser(id)
const user = await User.findById(id)

if (!user) {
throw new NotFoundError('No user found')
Expand Down
4 changes: 2 additions & 2 deletions staff/belen-ivars/project/api/logic/retrieveRecipes.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import random from './helpers/random.js'
import retrieveRecipes from './retrieveRecipes.js'
import { errors } from 'com'
import { User, Recipe } from '../data/models.js'
import { NotFoundError } from 'com/errors.js'
const { NotFoundError } = errors
const { ObjectId } = mongoose.Types

describe('retrieveRecipes', () => {
Expand Down Expand Up @@ -67,7 +67,7 @@ describe('retrieveRecipes', () => {
throw new Error('should not reach this point')
} catch (error) {
expect(error).to.be.instanceOf(NotFoundError)
expect(error.message).to.equal('no user found')
expect(error.message).to.equal('No user found')
}
})
after(async () => await mongoose.disconnect())
Expand Down
53 changes: 53 additions & 0 deletions staff/belen-ivars/project/api/test/retrieve-recipes.test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
source pepetest.sh

TEST 'retrieve-recipes'

CASE 'success on current user'

curl 'http://localhost:9000/recipes/65f85ac7883fd3713c8bd3a3' \
-H 'Authorization: Bearer 65f85ac7883fd3713c8bd3a3' \
-v

# > GET /recipes/65f85ac7883fd3713c8bd3a3 HTTP/1.1
# > Host: localhost:9000
# > User-Agent: curl/8.4.0
# > Accept: */*
# > Authorization: Bearer 65f85ac7883fd3713c8bd3a3
# >
# < HTTP/1.1 200 OK
# < X-Powered-By: Express
# < Access-Control-Allow-Origin: *
# < Content-Type: application/json; charset=utf-8
# < Content-Length: 1125
# < ETag: W/"465-DMOd83RcJKRMoeR/PypUE8SJ5aU"
# < Date: Tue, 09 Apr 2024 17:37:27 GMT
# < Connection: keep-alive
# < Keep-Alive: timeout=5
# <
# * Connection #0 to host localhost left intact
# [{"_id":"65f883f4fb135521e8161c93","title":"Colors","description":"Persona con pintura corporal","image":"https://www.pexels.com/es-es/foto/persona-con-pintura-corporal-1209843/","author":"65d655fac1dd88f9aee917d6","__v":0},{"_id":"65f97adbd699fa7945c5d178","title":"Colors","description":"Persona con pintura corporal","image":"https://www.pexels.com/es-es/foto/persona-con-pintura-corporal-1209843/","author":"65d655fac1dd88f9aee917d6","__v":0},{"_id":"65f97ae4ee6c8ad8251da2b0","title":"Colors","description":"Persona con pintura corporal","image":"https://www.pexels.com/es-es/foto/persona-con-pintura-corporal-1209843/","author":"65d655fac1dd88f9aee917d6","__v":0},{"_id":"65fc725721104edb3ca0821b","title":"Colors","description":"Persona con pintura corporal","image":"https://www.pexels.com/es-es/foto/persona-con-pintura-corporal-1209843/","author":"65d655fac1dd88f9aee917d6","__v":0},{"_id":"65fc7fbf9c9ec7ea25f03601","title":"sdfgs","description":"srfwerf","image":"https://sorprendele.es/storage/2022/11/tassa-de-la-terreta-menges-mes-que-el-tio-sangonera-600x600.jpg","author":"65f85ac7883fd3713c8bd3a3","__v":0}]

CASE "fail on non existing user"

curl 'http://localhost:9000/recipes/65d642e9695ce01b53585a84' \
-H 'Authorization: Bearer 65d642e9695ce01b53585a84' \
-v

# > GET /recipes/65d642e9695ce01b53585a84 HTTP/1.1
# > Host: localhost:9000
# > User-Agent: curl/8.4.0
# > Accept: */*
# > Authorization: Bearer 65d642e9695ce01b53585a84
# >
# < HTTP/1.1 404 Not Found
# < X-Powered-By: Express
# < Access-Control-Allow-Origin: *
# < Content-Type: application/json; charset=utf-8
# < Content-Length: 24
# < ETag: W/"18-dMQu7DCvMLzkIB4OfTQNazIjBKo"
# < Date: Tue, 09 Apr 2024 17:37:27 GMT
# < Connection: keep-alive
# < Keep-Alive: timeout=5
# <
# * Connection #0 to host localhost left intact
# {"name":"NotFoundError"}%
47 changes: 47 additions & 0 deletions staff/belen-ivars/project/app/src/components/Recipe.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'

import logic from "../logic"

import { Button, Field, Form, Link } from "../library"
import { useContext } from '../hooks'

import session from '../logic/session'

function Recipe(props) {

console.log('Recipe')
const [view, setView] = useState(null)

const context = useContext()
const navigate = useNavigate()



return <article className="recipe">
{/* <h2><Link onClick={handleUserClick}> {props.recipe.author.name}</Link></h2> */}

<h2> {props.recipe.title}</h2>
<img className="recipe-image" src={props.recipe.image} />
<p>{props.recipe.description}</p>

{/* {view === null && <p>{props.recipe.text}</p>} */}

{/* {view === 'edit' && <Form onSubmit={handleEditSubmit}>
<Field id="text" value={props.recipe.text} />
<Button type="submit">Save</Button>
<Button onClick={handleEditCancelClick}>Cancel</Button>
</Form>} */}


{/* <div className="recipe-actions">
<Button onClick={handleToggleLikeClick}>{props.recipe.liked ? '❤️' : '🤍'} {props.recipe.likes.length}</Button>
<Button onClick={handleToggleFavClick}>{props.recipe.fav ? '⭐️' : '✩'}</Button>
{session.sessionUserId === props.recipe.author.id && <Button onClick={handleDeleteRecipeClick}>🗑️</Button>}
{session.sessionUserId === props.recipe.author.id && view === null && <Button onClick={handleEditclick}>✏️</Button>}
</div> */}
</article>
}

export default Recipe
37 changes: 36 additions & 1 deletion staff/belen-ivars/project/app/src/components/Recipes.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,38 @@
function Recipes(props) { }
import { useEffect, useState } from "react"
import Recipe from './Recipe'
import { useContext } from "../hooks"
import logic from "../logic"

function Recipes(props) {
console.log('Recipes')

const [recipes, setRecipes] = useState([])

const context = useContext()

const refreshRecipes = () => {
(async () => {

try {
const content = await logic.retrieveRecipes()

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

useEffect(() => {
console.log('Recipes effect')

refreshRecipes()
}, [props.stamp])

return <div className="recipes">
{recipes.map(recipe => <Recipe key={recipe.id} recipe={recipe} onError={props.onError} />)}
</div>

}

export default Recipes
4 changes: 3 additions & 1 deletion staff/belen-ivars/project/app/src/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import MethodFilter from './MethodFilter'
import SearchForm from './SearchForm'
import TimeFilter from './TimeFilter'
import TopProfileImage from './TopProfileImage'
import Recipe from './Recipe'


export {
Expand All @@ -20,5 +21,6 @@ export {
MethodFilter,
SearchForm,
TimeFilter,
TopProfileImage
TopProfileImage,
Recipe
}
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 @@ -4,14 +4,16 @@ import logoutUser from './logoutUser'
import retrieveUser from './retrieveUser'
import isUserLoggedIn from './isUserLoggedIn'
import createRecipe from './createRecipe'
import retrieveRecipes from './retrieveRecipes'

const logic = {
registerUser,
loginUser,
logoutUser,
retrieveUser,
isUserLoggedIn,
createRecipe
createRecipe,
retrieveRecipes
}

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

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

let res
try {
res = await fetch(`${API_URL}/recipes/${session.sessionUserId}`, req)
} catch (error) {
throw new SystemError(error.message)
}

if (!res.ok) {
let body

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

throw new errors[body.error](body.message)
}

try {
const recipes = await res.json()

return recipes
} catch (error) {
throw new SystemError(error.message)
}
})()
}
3 changes: 2 additions & 1 deletion staff/belen-ivars/project/app/src/pages/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import FavsUser from "./FavsUser"
import FullHeader from "../components/FullHeader"
import Context from "../Context"
import NewRecipe from "../components/NewRecipeForm"
import { Recipes } from "../components"


function Home(props) {
Expand Down Expand Up @@ -49,7 +50,6 @@ function Home(props) {
function handleNewRecipeClick() {

setView('new-recipe')
//Component i lògica per a fer de 0, o bé, copiant de newPost
}

function handleNewRecipeCancel() {
Expand Down Expand Up @@ -77,6 +77,7 @@ function Home(props) {
<Route path="/profile" element={<Profile />} />
<Route path='/favs' element={<FavsUser />} />
<Route path='/new-recipe' element={<NewRecipe />} />
<Route path='/' element={<Recipes stamp={stamp} />} />



Expand Down
Loading

0 comments on commit 26e3231

Please sign in to comment.