Skip to content

Commit

Permalink
Merge pull request #3 from deepsingh132/development
Browse files Browse the repository at this point in the history
Refactor: Replace useEffect with SWR 2.0 for improved data fetching
  • Loading branch information
deepsingh132 authored Dec 5, 2023
2 parents ad804ad + d5d0550 commit b485279
Show file tree
Hide file tree
Showing 38 changed files with 874 additions and 616 deletions.
32 changes: 32 additions & 0 deletions @types/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
type Post = {
content?: string | null;
name: string;
username: string;
authorID: string;
category?:
| "art"
| "music"
| "hybrid"
| "theatre"
| "literature"
| "science"
| "sports"
| "other";
tags?: string[];
image?: string;
featured?: boolean;
likes?: string[];
comments?: {
userId: string;
content: string;
username: string;
timestamp: string;
userImg: string;
url: string;
name: string;
}[];
userImg?: string;
url?: string | null;
createdAt?: string;
updatedAt?: string;
};
8 changes: 5 additions & 3 deletions app/[username]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import Navbar from "@/components/Navbar";
import Sidebar from "@/components/Sidebar";
import Widgets from "@/components/Widgets";
import UserProfileData from "@/components/UserProfileData";
import CommentModal from "@/components/CommentModal";
import PostModal from "@/components/PostModal";
import { backendUrl } from "../utils/config/backendUrl";

export default async function UserProfile({}) {
const { trendingPosts, randomUsersResults } = await getWidgetsData();
Expand All @@ -23,6 +24,7 @@ export default async function UserProfile({}) {
trendingPosts={trendingPosts || []}
randomUsersResults={randomUsersResults?.results || []}
/>
<PostModal updatePosts={undefined} type={"post"} />
<CommentModal updatePosts={undefined} type={undefined} />
</main>
);
Expand All @@ -32,15 +34,15 @@ export default async function UserProfile({}) {

async function getWidgetsData() {

if (!process.env.NEXT_PUBLIC_BACKEND_URL) {
if (!backendUrl) {
return {
trendingPosts: [],
randomUsersResults: [],
};
}

const trendingPosts = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/widgets/trending/posts`
`${backendUrl}/widgets/trending/posts`
).then((res) => res.json());

// Who to follow section
Expand Down
24 changes: 12 additions & 12 deletions app/api/posts/[id]/comment/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,32 @@ import { NextResponse } from "next/server";
// Private route handle post update
export async function PUT(request: Request) {
const bearer = request.headers.get("Authorization");
const userId = request.headers.get("userId");

if (!bearer) {
return NextResponse.json({ message: "Not authorized" }, { status: 401 });
}

const token = bearer.split(" ")[1];
const data = await request.json();
const postId = request.url.split("/")[5];
const userId = data?.userId;

await connectMongoDB();

const post = await Post.findOne({ _id: postId }).lean() as any;

if (!post) {
return NextResponse.json({ message: "No posts found" }, { status: 404 });
}

const { _id, username, name, userImg, content, timestamp, url } = await request.json();

const newComment = {
_id: new mongoose.Types.ObjectId(),
_id: _id,
userId: userId,
content: data.content,
username: data.username,
timestamp: data.timestamp,
url: data.url,
userImg: data.userImg,
name: data.name,
content: content,
username: username,
timestamp: timestamp,
url: url,
userImg: userImg,
name: name,
};

post.comments.push(newComment);
Expand Down Expand Up @@ -73,7 +73,7 @@ export async function DELETE(request: Request) {

await post.updateOne({ comments: newComments });

return NextResponse.json({ post: post }, { status: 200 });
return NextResponse.json({ message: "Comment deleted" }, { status: 200 });
} catch (error) {
console.error("Error: ", error);
return NextResponse.json({ message: "Something went wrong" }, { status: 500 });
Expand Down
3 changes: 1 addition & 2 deletions app/api/posts/[id]/like/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { NextResponse } from "next/server";
// Private route handle post update
export async function PUT(request: Request) {
const postId = request.url.split("/")[5];
const data = await request.json();
const userId = data?.userId;
const userId = request.headers.get("userId");

if (!postId || !userId) {
return NextResponse.json({ message: "Invalid data" }, { status: 400 });
Expand Down
43 changes: 32 additions & 11 deletions app/api/posts/route.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
import { connectMongoDB } from "@/libs/mongodb";
import Post from "../../../models/Post";
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
try {
await connectMongoDB();
const type = req.nextUrl.searchParams.get("type") || null;

export async function GET() {
await connectMongoDB();
const posts = await Post.find({}); // fetch data from the source
return NextResponse.json({ posts }); // respond with JSON
if (type) {
const posts = await Post.find({ category: type });
return NextResponse.json({ posts });
}

const posts = await Post.find({}); // fetch data from the source
return NextResponse.json({ posts }); // respond with JSON
} catch (error) {
console.error("Error fetching posts: ", error);
return NextResponse.json({ message: "Error fetching posts from MongoDB!" });
}
}

// Private route, handle post creation
export async function POST(req) {
try {
const { username, name, userImg, content, authorID, category, url } = await req.json();
const { _id, username, name, userImg, content, authorID, category, url } =
await req.json();
await connectMongoDB();
const res = await Post.create({ username, name, userImg, content, authorID, category, url });
const res = await Post.create({
_id,
username,
name,
userImg,
content,
authorID,
category,
url,
});
return NextResponse.json({ message: "success", post: res });
} catch (error) {
console.error("Error creating post: ", error);
return NextResponse.json({ message: "error: ", error });
}
} catch (error) {
console.error("Error creating post: ", error);
return NextResponse.json({ message: "error: ", error });
}
}
2 changes: 1 addition & 1 deletion app/api/widgets/trending/posts/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function GET(request: Request) {
return NextResponse.json({ trendingPosts }, { status: 200 });
} catch (error) {
console.error("Error fetching popular posts:", error);
return NextResponse.json({ error: "Failed to fetch popular posts" }, { status: 500 });
return new NextResponse("Error!", { status: 500 });
}
}

10 changes: 8 additions & 2 deletions app/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Sidebar from "../../components/Sidebar";
import Navbar from "../../components/Navbar";
import { PaperAirplaneIcon } from "@heroicons/react/24/outline";
import { useEffect, useState, useRef } from "react";
import PostModal from "@/components/PostModal";

export default function Chat({}) {
const [chats, setChats] = useState<any>([]);
Expand Down Expand Up @@ -151,14 +152,18 @@ export default function Chat({}) {
</div>
<div className="chatLayout flex flex-col md:ml-96 w-full h-screen relative">
<div className="chatLayout transition-all duration-300 pt-20 pb-48 overflow-auto px-4 flex h-screen bg-gray-200 dark:bg-darkBg flex-col w-full">
<ChatBubble user={true} message={"Hello"} timestamp={Date.now() - 1000} />
<ChatBubble
user={true}
message={"Hello"}
timestamp={Date.now() - 1000}
/>
<ChatBubble
user={false}
message={"Hi"}
timestamp={Date.now()}
/>

{chats.map((chat : any) => (
{chats.map((chat: any) => (
<ChatBubble
key={chat.id}
user={chat.user}
Expand Down Expand Up @@ -189,6 +194,7 @@ export default function Chat({}) {
</div>
</div>
</div>
<PostModal updatePosts={undefined} type={"post"} />
</main>
);
}
108 changes: 56 additions & 52 deletions app/events/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import EventsLayout from "@/components/EventsLayout";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import Login from "../login/page";
import PostModal from "@/components/PostModal";
import { backendUrl } from "../utils/config/backendUrl";

export default async function Event({}) {

Expand Down Expand Up @@ -43,68 +45,70 @@ export default async function Event({}) {
</div>
</div>
<Widgets
trendingPosts={trendingPosts || []}
randomUsersResults={randomUsersResults?.results || []}
trendingPosts={trendingPosts}
randomUsersResults={randomUsersResults}
/>
<PostModal updatePosts={undefined} type={"post"} />
</div>
</main>
);
}

async function getEvents(session: any) {
async function getEvents(session: any) {

if (!process.env.NEXT_PUBLIC_BACKEND_URL) {
return {
events: [],
};
}

const res = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/events`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${session?.user?.accessToken}`,
},
if (!backendUrl || backendUrl === "undefined") {
return {
events: [],
};
}
);
const data = await res.json();

return {
events: data?.events || [],
};
}

async function getWidgetsData() {

if (!process.env.NEXT_PUBLIC_BACKEND_URL) {
return {
trendingPosts: [],
randomUsersResults: [],
};
try {
const res = await fetch(`${backendUrl}/events`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session?.user?.accessToken}`,
},
});
const data = await res.json();

return {
events: data?.events || [],
};
} catch (error) {
return {
events: [],
};
}
}

const trendingPosts = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/widgets/trending/posts`
).then((res) => res.json());

// Who to follow section

let randomUsersResults : any = [];

try {
const res = await fetch(
"https://randomuser.me/api?results=10&inc=name,login,picture"
);
async function getWidgetsData() {
if (!backendUrl || backendUrl === "undefined") {
return {
trendingPosts: [],
randomUsersResults: [],
};
}

randomUsersResults = await res.json();
} catch (e) {
randomUsersResults = [];
try {
const trendingPostsRes = await fetch(
`${backendUrl}/widgets/trending/posts`
);
const randomUsersRes = await fetch(
"https://randomuser.me/api/?results=10&inc=name,login,picture"
);

const trendingPosts = await trendingPostsRes.json();
const randomUsersResults = await randomUsersRes.json();

return {
trendingPosts: trendingPosts.trendingPosts,
randomUsersResults: randomUsersResults.results,
};
} catch (error) {
return {
trendingPosts: [],
randomUsersResults: [],
};
}
}

return {
trendingPosts: trendingPosts?.trendingPosts,
randomUsersResults,
};
}
Loading

0 comments on commit b485279

Please sign in to comment.