Skip to content

Commit

Permalink
feat: updates a couple more buttons to hopefully finish lib
Browse files Browse the repository at this point in the history
  • Loading branch information
SilveerDusk committed May 31, 2024
1 parent 097c408 commit 4b2e5d5
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 75 deletions.
3 changes: 2 additions & 1 deletion backend/routes/basketRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import express from "express";
import { Request, Response } from "express";
import Basket, { IBasket } from "../models/basketSchema";
import connectDB from "../connection";
import { ObjectId } from "mongoose";

const router = express.Router();

Expand Down Expand Up @@ -85,7 +86,7 @@ router.patch("/:id", async (req: Request, res: Response) => {

try {
connectDB();

console.log(updatedData);
const updatedBasket = await Basket.findByIdAndUpdate(id, updatedData, {
new: true,
runValidators: true,
Expand Down
42 changes: 39 additions & 3 deletions frontend/lib/edits.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ObjectId } from "mongoose";
import { IBasket } from "../../backend/models/basketSchema";
import { IItem } from "../../backend/models/itemSchema";
import { IUser } from "../../backend/models/userSchema";
import { IGroup } from "backend/models/groupSchema";

type updatedGroup = {
groupName: string;
Expand Down Expand Up @@ -35,7 +37,7 @@ export const addGroupToUser = async (user: IUser, groups: string[]) => {
});
};

export const editGroup = async (groupId: string, groupData: updatedGroup) => {
export const editGroup = async (groupId: ObjectId, groupData: updatedGroup) => {
return fetch(`http://localhost:3001/groups/${groupId}`, {
method: "PATCH",
headers: {
Expand All @@ -58,13 +60,13 @@ export const editBasket = async (
});
};

export const addItemToBasket = async (basketId: string, newItems: string[]) => {
export const addItemToBasket = async (basketId: ObjectId, basketItems: ObjectId[]) => {
return fetch(`http://localhost:3001/baskets/${basketId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newItems),
body: JSON.stringify({items: basketItems}),
});
};

Expand Down Expand Up @@ -152,3 +154,37 @@ export const editUser = async (
body: JSON.stringify(userData),
});
};

export const addBasketToGroup = async (
group: IGroup,
baskets: ObjectId[],
) => {
return fetch(
`http://localhost:3001/groups/${group._id}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ baskets: baskets }),
}
);
}

export const addUserToGroup = async (
group: IGroup,
users: ObjectId[],
) => {
return fetch(
`http://localhost:3001/groups/${group._id}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ members: users }),
}
);
}
2 changes: 1 addition & 1 deletion frontend/lib/fetches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const fetchGroupById = async (groupId: string) => {
}
};

export const fetchUser = async (userId: string) => {
export const fetchUser = async (userId: ObjectId) => {
return fetch(`http://localhost:3001/users/${userId}`);
};

Expand Down
19 changes: 18 additions & 1 deletion frontend/lib/posts.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ObjectId } from "mongodb";
import { ObjectId } from "mongoose";

type newUser = {
username: string;
Expand All @@ -24,6 +24,12 @@ type credentials = {
password: string;
};

type basketData = {
basketName: string;
description: string;
members: ObjectId[];
};

export const createUser = async (user: newUser) => {
return fetch("http://localhost:3001/users", {
method: "POST",
Expand Down Expand Up @@ -65,3 +71,14 @@ export const createNewGroup = async (groupData: any) => {
body: JSON.stringify(groupData),
});
};

export const createNewBasket = async (basketData: basketData) => {
return fetch("http://localhost:3001/baskets/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify(basketData),
});
}
22 changes: 6 additions & 16 deletions frontend/src/components/AddFriendToBasket.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
PopoverArrow,
} from "@chakra-ui/react";
import { IUser } from "../../../backend/models/userSchema";
import { fetchBasket } from "../../lib/fetches";
import { editBasket } from "../../lib/edits";

interface Props {
basketId: string;
Expand All @@ -36,29 +38,17 @@ const AddFriendToBasket: React.FC<Props> = ({
);
}, [memberid, currentUserId]);

// Function to handle button click and log members to the console
const handleLogMembers = () => {
console.log("Members:", members);
};
const AddToBasket = async (basketId: string, friendId: string) => {
try {
const res = await fetch(`http://localhost:3001/baskets/${basketId}`);
const res = await fetchBasket(basketId);
let basket;
if (res.ok) {
basket = await res.json();
if (!basket.members.includes(friendId)) {
basket.members.push(friendId);
console.log("Pushed friend ID to basket's member list");
const updatedRes1 = await fetch(
`http://localhost:3001/baskets/${basketId}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ members: basket.members }),
},
);
const updatedRes1 = await editBasket(basketId, basket);

if (updatedRes1.ok) {
console.log("Friend added to group's member list successfully");
} else {
Expand All @@ -73,6 +63,7 @@ const AddFriendToBasket: React.FC<Props> = ({
} catch (error) {
console.error("Error adding friend:", error);
}
window.location.reload();
};

return (
Expand All @@ -86,7 +77,6 @@ const AddFriendToBasket: React.FC<Props> = ({
bg: "var(--col-tertiary)",
color: "var(--col-dark)",
}}
onClick={handleLogMembers}
>
Add Users
</Button>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/EditBasket.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ const EditBasket: React.FC<Props> = ({ basketId }) => {
} catch (error) {
console.error("Error updating profile:", error);
}
window.location.reload();
};

return (
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/EditGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ const Editgroup: React.FC<Props> = ({ GroupId }) => {
} catch (error) {
console.error("Error updating profile:", error);
}
window.location.reload();
};

return (
Expand Down
38 changes: 15 additions & 23 deletions frontend/src/components/NewBasketOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { FormEvent, useState } from "react";
import "../styles/JoinGroup.css";
import { IUser } from "../../../backend/models/userSchema";
import { IGroup } from "../../../backend/models/groupSchema";
import { addBasketToGroup } from "../../lib/edits";
import { createNewBasket } from "../../lib/posts";

const NewBasketOptions = ({
user,
Expand All @@ -31,34 +33,23 @@ const NewBasketOptions = ({
// 1) When added, update "owner" keyword to be automatically the id of the logged in user
// 2) If no user logged in, impossible to create group
const createBasket = async (basketName: string, description: string) => {
const promise = await fetch("http://localhost:3001/baskets/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({
basketName,
description,
members: [user?._id],
}), //dummyUserId will need to be replaced
});
if (user === null) {
console.error("No user logged in");
return;
}
const basketData = {
basketName: basketName,
description: description,
members: [user._id]
};
const promise = await createNewBasket(basketData);
if (promise.status === 201) {
const data = await promise.json();
console.log("Basket created successfully", data);
const newData = [...group.baskets, data._id];
console.log(newData);
const groupPromise = await fetch(
`http://localhost:3001/groups/${group._id}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ baskets: newData }),
},
);
const groupPromise = await addBasketToGroup(group, newData);

if (groupPromise.status === 200) {
const groupData = await groupPromise.json();
updateGroup(groupData);
Expand Down Expand Up @@ -107,6 +98,7 @@ const CreateGroup = ({ postBasket }: CreateProps) => {
basket.description === "" ? "No description given" : basket.description,
);
setBasket({ name: "", description: "" });

};

return (
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/components/NewItemOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { AddIcon } from "@chakra-ui/icons";
import { fetchBasket } from "../../lib/fetches";
import { createNewItem } from "../../lib/posts";
import { addItemToBasket } from "../../lib/edits";
import { ObjectId } from "mongoose";
import { IBasket } from "../../../backend/models/basketSchema";

const NewItemOptions = ({
basket,
Expand All @@ -43,7 +45,7 @@ const NewItemOptions = ({
const res = await fetchBasket(basket);

if (res.ok) {
const currentBasket = await res.json();
const currentBasket = await res.json() as IBasket;
const payload = {
name,
toShare,
Expand All @@ -59,7 +61,7 @@ const NewItemOptions = ({

if (promise.status === 201) {
const data = await promise.json();
const newData = [...currentBasket.items, data._id] as string[];
const newData = [...currentBasket.items, data._id] as ObjectId[];
const basketPromise = await addItemToBasket(currentBasket._id, newData);

if (basketPromise.status === 200) {
Expand Down
35 changes: 10 additions & 25 deletions frontend/src/components/SendInvite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
PopoverArrow,
} from "@chakra-ui/react";
import { IUser } from "../../../backend/models/userSchema";
import { fetchGroupById, fetchUser } from "../../lib/fetches";
import { ObjectId } from "mongoose";
import { addGroupToUser, addUserToGroup } from "../../lib/edits";

interface Props {
groupId: string | undefined;
Expand Down Expand Up @@ -39,11 +42,11 @@ const SendInviteToGroup: React.FC<Props> = ({ groupId, friends, members }) => {
console.log("friends:", friendsNotInGroup);
console.log("friend Users:", friends);
};
const addToGroup = async (friendId: string, groupId: string | undefined) => {
const addToGroup = async (friendId: ObjectId, groupId: string) => {
try {
const res1 = await fetch(`http://localhost:3001/groups/${groupId}`);
const res1 = await fetchGroupById(groupId);
const res = await fetchUser(friendId);

const res = await fetch(`http://localhost:3001/users/${friendId}`);
let friend;
let group;
if (res.ok && res1.ok) {
Expand All @@ -52,16 +55,7 @@ const SendInviteToGroup: React.FC<Props> = ({ groupId, friends, members }) => {
if (!group.members.includes(friendId)) {
group.members.push(friendId);
console.log("Pushed friend ID to group's member list");
const updatedRes1 = await fetch(
`http://localhost:3001/groups/${groupId}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ members: group.members }),
},
);
const updatedRes1 = await addUserToGroup(group, group.members);
if (updatedRes1.ok) {
console.log("Friend added to group's member list successfully");
} else {
Expand All @@ -72,16 +66,7 @@ const SendInviteToGroup: React.FC<Props> = ({ groupId, friends, members }) => {
friend.groups.push(groupId);
console.log("Pushed to list");

const updatedRes = await fetch(
`http://localhost:3001/users/${friendId}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ groups: friend.groups }),
},
);
const updatedRes = await addGroupToUser(friend, friend.groups);
if (updatedRes.ok) {
console.log("Friend added to group successfully");
} else {
Expand Down Expand Up @@ -129,7 +114,7 @@ const SendInviteToGroup: React.FC<Props> = ({ groupId, friends, members }) => {
Friends not in this Group
</PopoverHeader>
<PopoverBody>
{friendsNotInGroup.length > 0 ? (
{groupId!=undefined && friendsNotInGroup.length > 0 ? (
<ul>
{friendsNotInGroup.map((friend) => (
<li
Expand All @@ -144,7 +129,7 @@ const SendInviteToGroup: React.FC<Props> = ({ groupId, friends, members }) => {
<span>{friend.username}</span>
<Button
size="sm"
onClick={() => addToGroup(friend._id.toString(), groupId)}
onClick={() => addToGroup(friend._id, String(groupId))}
>
Add to Group
</Button>
Expand Down
Loading

0 comments on commit 4b2e5d5

Please sign in to comment.