Skip to content

Commit

Permalink
feat: add selectedBosses route, fix mobile bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
dstudnicki committed Aug 24, 2024
1 parent 7c8522c commit 984d78a
Show file tree
Hide file tree
Showing 8 changed files with 148 additions and 30 deletions.
1 change: 1 addition & 0 deletions src/app/api/auth/register/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { MongoClient, ObjectId } from "mongodb";
import { number } from "zod";

const client = new MongoClient(process.env.MONGODB_URI ?? "");

Expand Down
2 changes: 1 addition & 1 deletion src/app/api/bosses/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export async function PATCH(request: Request) {
if (alreadySelected) {
await userCollection.updateOne({ id: userId }, { $pull: { selectedBosses: id } });
} else {
await userCollection.updateOne({ id: userId }, { $addToSet: { selectedBosses: id } });
await userCollection.updateOne({ id: userId }, { $addToSet: { selectedBosses: { id } } });
}

return NextResponse.json({ message: "Updated successfully" });
Expand Down
66 changes: 66 additions & 0 deletions src/app/api/selectedBosses/route.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { NextResponse } from "next/server";
import { MongoClient, ObjectId } from "mongodb";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/authOptions";

const client = new MongoClient(process.env.MONGODB_URI ?? "");
// const isValidObjectId = (id: string) => /^[a-fA-F0-9]{24}$/.test(id);

export async function GET() {
const session = await getServerSession(authOptions);
const userId = (session?.user as any).id;

try {
await client.connect();
const db = client.db("elden-ring");
const userCollection = db.collection("users");

const user = await userCollection.findOne({ id: userId });

if (!user) {
return NextResponse.json({ message: "User not found" }, { status: 404 });
}

const selectedBosses = user.selectedBosses;

return NextResponse.json(selectedBosses);
} catch (error) {
console.error("Error processing GET request:", error);
return NextResponse.error();
} finally {
await client.close();
}
}

// export async function PATCH(request: Request) {
// const { id } = await request.json();
// const session = await getServerSession(authOptions);

// const userId = (session?.user as any).id;

// if (!isValidObjectId(id) || !userId) {
// return NextResponse.json({ message: "Invalid ID format" }, { status: 400 });
// }

// try {
// await client.connect();
// const db = client.db("elden-ring");
// const userCollection = db.collection("users");

// const user = await userCollection.findOne({ id: userId });
// const alreadySelected = user?.selectedBosses.includes(id);

// if (alreadySelected) {
// await userCollection.updateOne({ id: userId }, { $pull: { selectedBosses: id } });
// } else {
// await userCollection.updateOne({ id: userId }, { $addToSet: { selectedBosses: id } });
// }

// return NextResponse.json({ message: "Updated successfully" });
// } catch (error) {
// console.error("Error processing PATCH request:", error);
// return NextResponse.error();
// } finally {
// await client.close();
// }
// }
54 changes: 44 additions & 10 deletions src/app/bosses/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import axios from "axios";
import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";

export default function BossesPage() {
const baseURL = process.env.NEXT_PUBLIC_BASE_URL;
Expand All @@ -21,11 +22,12 @@ export default function BossesPage() {
const userId = session && session.user ? (session?.user as any).id : null;

const [data, setData] = useState([]);
const [selectedBosses, setSelectedBosses] = useState([]);
const [isSelected, setIsSelected] = useState<{ [key: string]: any }>({});
const [open, setOpen] = useState(false);
const [value, setValue] = useState("");
const [loading, setLoading] = useState(true);
const dataLocations = data.map((boss: any) => boss.location);
const dataLocations = data.map((boss: any) => boss.region);

const filteredLocations = (a: any[]) => {
var seen: { [key: string]: boolean } = {};
Expand All @@ -34,6 +36,24 @@ export default function BossesPage() {
});
};

const findMatchingBosses = (dataArray: any[], selectedArray: any[]) => {
return dataArray.filter((boss) => selectedArray.some((selectedBoss) => selectedBoss.id === boss.id));
};

useEffect(() => {
if (data.length > 0 && selectedBosses.length > 0) {
const matchingBosses = findMatchingBosses(data, selectedBosses);
console.log(matchingBosses);
matchingBosses.forEach((boss) => {
console.log(`Boss found: ${boss.name}`);
});
}
}, [data, selectedBosses]);

if (!session) {
redirect("/login");
}

const locationsForFilter = filteredLocations(dataLocations);

const fetchData = async () => {
Expand All @@ -52,6 +72,20 @@ export default function BossesPage() {
}
};

const fetchSelectedBosses = async () => {
try {
const response = await axios.get(`${currentEnv}/api/selectedBosses`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userId}`,
},
});
setSelectedBosses(response.data);
} catch (error) {
console.error("Error fetching selected bosses:", error);
}
};

const toggleSelected = async (id: string, name: string) => {
if (!session || !session.user) {
toast.error("You need to be logged in to select a boss");
Expand Down Expand Up @@ -103,14 +137,15 @@ export default function BossesPage() {

const showFilteredData = () => {
if (value) {
return data.filter((boss: any) => boss.location === value);
return data.filter((boss: any) => boss.region === value);
} else {
return data;
}
};

useEffect(() => {
fetchData();
fetchSelectedBosses();
}, []);

return (
Expand All @@ -121,7 +156,7 @@ export default function BossesPage() {
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" aria-expanded={open} className="w-[200px] justify-between">
{value ? locationsForFilter.find((location) => location === value) : "Select location..."}
{value ? locationsForFilter.find((region) => region === value) : "Select location..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
Expand All @@ -131,16 +166,16 @@ export default function BossesPage() {
<CommandList>
<CommandEmpty>No location found.</CommandEmpty>
<CommandGroup>
{locationsForFilter.map((location) => (
{locationsForFilter.map((region) => (
<CommandItem
key={location}
value={location}
key={region}
value={region}
onSelect={(currentValue) => {
setValue(currentValue === value ? "" : currentValue);
setOpen(false);
}}>
<Check className={cn("mr-2 h-4 w-4", value === location ? "opacity-100" : "opacity-0")} />
{location}
<Check className={cn("mr-2 h-4 w-4", value === region ? "opacity-100" : "opacity-0")} />
{region}
</CommandItem>
))}
</CommandGroup>
Expand All @@ -151,8 +186,7 @@ export default function BossesPage() {
)}
<section className="grid sm:grid-cols-2 lg:grid-cols-4 grid-rows-1 gap-4 mt-2">
{loading
? // Display skeleton loaders when loading
Array.from({ length: 8 }).map((_, index) => (
? Array.from({ length: 8 }).map((_, index) => (
<div key={index} className="flex flex-col space-y-3 mt-8">
<Skeleton className="flex h-5 w-[250px] mb-2" />
<Skeleton className="h-[160px] w-[300px] rounded-xl" />
Expand Down
6 changes: 3 additions & 3 deletions src/components/loginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,12 @@ export default function LoginForm() {
</div>
</div>
<div className="flex flex-col gap-2">
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("github")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.gitHub className="mr-2 h-4 w-4" />} GitHub
</Button>
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("google")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.google className="mr-2 h-4 w-4" />} Google
</Button>
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("github")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.gitHub className="mr-2 h-4 w-4" />} GitHub
</Button>
</div>
</div>
);
Expand Down
39 changes: 28 additions & 11 deletions src/components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { signOut, useSession } from "next-auth/react";
export default function Navbar({ className, ...props }: React.HTMLAttributes<HTMLElement>) {
const { data: session } = useSession();

// function classNames(...classes: string[]) {
// return classes.filter(Boolean).join(" ")
// }

const dynamicRoute = !session && "/bosses" ? "/register" : "/bosses";
const pathname = usePathname();
const [selectedLink, setSelectedLink] = useState<string | null>(null);
Expand Down Expand Up @@ -72,7 +76,6 @@ export default function Navbar({ className, ...props }: React.HTMLAttributes<HTM
<DropdownMenuItem>Settings</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => signOut()}>Log out</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
Expand All @@ -83,18 +86,32 @@ export default function Navbar({ className, ...props }: React.HTMLAttributes<HTM
<a href="./">Home</a>
<a href={dynamicRoute}>Bosses</a>
</div>
<SheetFooter className="gap-2">
<SheetClose asChild>
<Button type="submit">
<a href="./register">Sign up</a>
</Button>
</SheetClose>
{session ? (
<SheetClose asChild>
<Button variant="secondary" type="submit">
<a href="./login">Sign in</a>
</Button>
<Link onClick={() => signOut()} href="./register">
<Button className="w-full" type="submit">
Log out
</Button>
</Link>
</SheetClose>
</SheetFooter>
) : (
<SheetFooter className="gap-2">
<SheetClose asChild>
<Link href="./register">
<Button className="w-full" type="submit">
Sign up
</Button>
</Link>
</SheetClose>
<SheetClose asChild>
<Link href="./login">
<Button className="w-full" variant="secondary" type="submit">
Sign in
</Button>
</Link>
</SheetClose>
</SheetFooter>
)}
</SheetContent>
</Sheet>
</div>
Expand Down
6 changes: 3 additions & 3 deletions src/components/user-auth-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
</div>
</div>
<div className="flex flex-col gap-2">
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("github")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.gitHub className="mr-2 h-4 w-4" />} GitHub
</Button>
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("google")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.google className="mr-2 h-4 w-4" />} Google
</Button>
<Button variant="outline" type="button" disabled={isLoading} onClick={() => signIn("github")}>
{isLoading ? <Icons.spinner className="mr-2 h-4 w-4 animate-spin" /> : <Icons.gitHub className="mr-2 h-4 w-4" />} GitHub
</Button>
</div>
</div>
);
Expand Down
4 changes: 2 additions & 2 deletions src/components/user-nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ export function UserNav() {
</DropdownMenu>
) : (
<>
<Button asChild variant="outline" className="py-2">
<Button asChild variant="outline">
<Link href="./login">Sign in</Link>
</Button>
<Button asChild className="py-2">
<Button asChild>
<Link href="./register">Sign up</Link>
</Button>
</>
Expand Down

0 comments on commit 984d78a

Please sign in to comment.