Skip to content

Commit

Permalink
connect random generator to db
Browse files Browse the repository at this point in the history
  • Loading branch information
Ella-zizzzy committed Apr 19, 2024
1 parent 4690777 commit 3bec407
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 41 deletions.
36 changes: 19 additions & 17 deletions back-end/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -455,24 +455,26 @@ server.post('/generator', auth, async(req, res) => {

});

server.post('/random', (req, res) => {
const { outfitName, items } = req.body;
// Validate input
if (!outfitName || items.length === 0) {
return res.status(400).json({ message: 'Outfit name and items are required.' });
server.post('/random', auth, async(req, res) => {
try {
const { outfitName, outfitNotes, items } = req.body;
const newOutfit = new Outfit({
outfitName:req.body.outfitName,
outfitNotes:req.body.outfitNotes,
Clothes:req.body.items,
user: req.user.id,
});

if (!outfitName || !items || items.length === 0) {
return res.status(400).json({ message: 'Outfit name and items are required.' });
}
await newOutfit.save();
res.status(201).json({ message: 'Outfit saved successfully' });

} catch ( error ) {
res.status(500).json({ message: 'Failed to add outfit', error: error });
}

// Construct the new outfit object
const newOutfit = {
outfitName,
notes:'',
items,
};

outfits.push(newOutfit);

// Send a success response
res.status(201).json({ message: 'New outfit generated and saved successfully.' });

});


Expand Down
115 changes: 91 additions & 24 deletions front-end/src/screens/RandomOutfitGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,54 @@ const RandomOutfitGenerator = () => {
const [allItems, setAllItems] = useState({ shirts: [], pants: [], skirts: [], shoes: [], accessories: [], jackets: [] });
const [generatedOutfit, setGeneratedOutfit] = useState([]);
const [outfitName, setOutfitName] = useState('');
const [outfitNotes, setOutfitNotes] = useState('');
const [showForm, setShowForm] = useState(false);

useEffect(() =>{
const token = localStorage.getItem('token');
const config = {
headers: {
Authorization: `Bearer ${token}`
}
};
axios.get('http://localhost:3001/verify_login', config)
.then( res => {
setShowForm(res.data.loggedIn)
})
.catch((e) => {
console.log(e)
})
}, []);

useEffect(() => {
const fetchItems = async () => {
try {
const categories = ['shirts', 'pants', 'skirts', 'shoes', 'accessories', 'jackets'];
const responses = await Promise.all(categories.map(category =>
axios.get(`http://localhost:3001/${category}`)
));
const itemsByCategory = {};
responses.forEach((response, index) => {
itemsByCategory[categories[index]] = response.data;
});
setAllItems(itemsByCategory);
const token = localStorage.getItem('token');
const config = {
headers: {
Authorization: `Bearer ${token}`
}
};

const responses = await Promise.all([
axios.get('http://localhost:3001/shirts', config),
axios.get('http://localhost:3001/pants', config),
axios.get('http://localhost:3001/skirts', config),
axios.get('http://localhost:3001/jackets', config),
axios.get('http://localhost:3001/shoes', config),
axios.get('http://localhost:3001/accessories', config),
]);
const categorizedItems = {
shirts: responses[0].data,
pants: responses[1].data,
skirts: responses[2].data,
jackets: responses[3].data,
shoes: responses[4].data,
accessories: responses[5].data,
};

setAllItems(categorizedItems);

} catch (error) {
console.error('Error fetching items:', error);
}
Expand All @@ -32,31 +67,55 @@ const RandomOutfitGenerator = () => {
const outfit = {};
const { shirts, pants, skirts, shoes, accessories, jackets } = allItems;

outfit.shirts = shirts[Math.floor(Math.random() * shirts.length)];
outfit.bottoms = Math.random() < 0.5
? pants[Math.floor(Math.random() * pants.length)]
: skirts[Math.floor(Math.random() * skirts.length)];
outfit.shoes = shoes[Math.floor(Math.random() * shoes.length)];
outfit.accessories = accessories[Math.floor(Math.random() * accessories.length)];
if (jackets.length && Math.random() < 0.5) {
if (shirts.length > 0) {
outfit.shirts = shirts[Math.floor(Math.random() * shirts.length)];
}
if (pants.length > 0 && skirts.length > 0) {
outfit.bottoms = Math.random() < 0.5
? pants[Math.floor(Math.random() * pants.length)]
: skirts[Math.floor(Math.random() * skirts.length)];
} else if (pants.length > 0) {
outfit.bottoms = pants[Math.floor(Math.random() * pants.length)];
} else if (skirts.length > 0) {
outfit.bottoms = skirts[Math.floor(Math.random() * skirts.length)];
}
if (jackets.length > 0 && Math.random() < 0.5) {
outfit.jackets = jackets[Math.floor(Math.random() * jackets.length)];
}

setGeneratedOutfit(Object.values(outfit));
if (shoes.length > 0) {
outfit.shoes = shoes[Math.floor(Math.random() * shoes.length)];
}
if (accessories.length > 0) {
outfit.accessories = accessories[Math.floor(Math.random() * accessories.length)];
}

const nonEmptyItems = Object.values(outfit).filter(item => item !== undefined);
setGeneratedOutfit(nonEmptyItems);
};

const handleOutfitNameChange = (e) => {
setOutfitName(e.target.value);
};

const handleOutfitNotesChange = (e) => {
setOutfitNotes(e.target.value);
};

const saveOutfit = async (e) => {
e.preventDefault();
try {
const token = localStorage.getItem('token');
const config = {
headers: {
Authorization: `Bearer ${token}`
}
};
await axios.post('http://localhost:3001/random', {
outfitName,
outfitNotes,
items: generatedOutfit,
});
// Optionally, reset state or redirect the user
},config);

} catch (error) {
console.error('Error saving the outfit:', error);
}
Expand All @@ -65,6 +124,7 @@ const RandomOutfitGenerator = () => {
const cancelOutfit = () => {
setGeneratedOutfit([]);
setOutfitName('');
setOutfitNotes('');
};

return (
Expand All @@ -82,13 +142,13 @@ const RandomOutfitGenerator = () => {
{generatedOutfit.length > 0 && (
<>
<div className="outfit-display">
{generatedOutfit.map((item, index) => (
<div key={index} className="item-container-random">
{generatedOutfit.map((item) => (
<div key={item._id} className="item-container-random">

<img src={`http://localhost:3001${item.img}`} alt={item.name}className="item-image-random" />
<img src={`http://localhost:3001${item.imgLink}`} alt={item.nameItem}className="item-image-random" />

<div className="item-info-random">
<p><u>{item.name}</u></p>
<p><u>{item.nameItem}</u></p>
<p>{item.brand}</p>
<p>{item.type}</p>
</div>
Expand All @@ -106,6 +166,13 @@ const RandomOutfitGenerator = () => {
onChange={handleOutfitNameChange}
required
/>
<input
name="outfitnotes"
type="text"
value={outfitNotes}
onChange={handleOutfitNotesChange}
placeholder='Leave any notes for this outfit :)'
/>
</form>
</div>
<div className="save-button-container">
Expand Down

0 comments on commit 3bec407

Please sign in to comment.