Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
thebkht committed Oct 25, 2023
1 parent 698508b commit 810011d
Show file tree
Hide file tree
Showing 21 changed files with 621 additions and 493 deletions.
69 changes: 17 additions & 52 deletions app/(Main)/[username]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,23 @@ export default async function Page({ params }: {
username: string
}
}) {
const rows = await postgres.user.findMany({
const user = await postgres.user.findFirst({
include: {
posts: true,
Followers: true,
Following: true
posts: {
orderBy: {
createdAt: "desc"
},
},
Followers: {
include: {
following: true
}
},
Followings: {
include: {
follower: true
}
}
},
where: {
username: params.username
Expand All @@ -28,7 +40,6 @@ export default async function Page({ params }: {

const session = await getServerSession();
console.log(session);
const user = rows[0];
if (!user) redirect("/404");

const posts = user.posts;
Expand All @@ -54,56 +65,10 @@ export default async function Page({ params }: {

const sessionUserName = await getSession();
console.log(sessionUserName);
// const [user, setUser] = useState<any | null>(null); // Replace 'any' with the actual type of your user data
// const [isLoaded, setIsLoaded] = useState<boolean>(false);
// const { status, data: session } = useSession();
//
//
// const [sessionUser, setSessionUser] = useState<any | null>(null);
// const [deleted, setDeleted] = useState<boolean>(false);
// const [posts, setPosts] = useState<any | null>(null);
// const router = useRouter();

// useEffect(() => {
// async function fetchData() {
// try {
// const userData = await getUserByUsername(params.username);
// setPosts(userData.posts);
// } catch (error) {
// console.error(error);
// }
// }

// fetchData();
// }, [deleted]);

// async function handleDelete(posturl: string) {
// await fetch(`/api/posts/${user?.username}?postid=${posturl}`, {
// method: "DELETE",
// });
// setDeleted(true);
// }


// if (!isLoaded) {
// // Loading skeleton or spinner while fetching data
// return (
// <div className="w-full max-h-screen flex justify-center items-center bg-background" style={
// {
// minHeight: "calc(100vh - 192px)"
// }
// }>
// <Icons.spinner className="h-10 animate-spin" />
// </div>
// )
// }




return (
<div className="Layout Layout--flowRow-until-md gap-2 lg:gap-6" >
<UserDetails user={user} followers={followers} followings={following} className="lg:w-[296px] md:w-64 w-full mx-auto" />
<UserDetails user={user} followers={followers} followings={following} />
<UserPosts posts={posts} className="row-span-2 md:col-span-2" user={user} sessionUser={sessionUserName} />
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion app/(Main)/feed/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function Feed() {
useEffect(() => {
async function fetchFeed() {
if (status !== "unauthenticated") {
const user = (await sessionUser).id
const user = (await sessionUser)?.id
try {
const response = await fetch(`/api/feed?user=${user}&page=${page}`);
if (!response.ok) {
Expand Down
2 changes: 1 addition & 1 deletion app/(Main)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function MainLayout({
return (
<>
{
status === 'authenticated' ? <Navbar /> : <LandingNavbar />
status != 'authenticated' ? <LandingNavbar /> : <Navbar />
}
<ScrollArea className='h-screen w-screen xl:px-36 2xl:px-64'>
<div className='py-24 px-4 lg:px-8 md:px-6 w-screen md:w-full'>
Expand Down
3 changes: 2 additions & 1 deletion app/(Main)/tag/[tagname]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import TagDetails from "@/components/tags/details";
import FollowTagButton from "@/components/tags/follow-btn";
import TagPosts from "@/components/tags/post";
import postgres from "@/lib/postgres";
import { getSession } from "next-auth/react";
import { getSession, } from "next-auth/react";
import { redirect } from "next/navigation";


Expand All @@ -17,6 +17,7 @@ export default async function TagPage({ params }: { params: { tagname: string }
},
include: {
followingtag: true,
_count: { select: { posts: true, followingtag: true } }
},
orderBy: {
posts: {
Expand Down
52 changes: 5 additions & 47 deletions app/api/feed/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { NextRequest, NextResponse } from 'next/server'

export async function GET(req: NextRequest, res: NextResponse) {
try {
const user_id = req.nextUrl.searchParams.get('user') as string
let page = parseInt(req.nextUrl.searchParams.get('page') || '0', 10)
const user_id = Number(req.nextUrl.searchParams.get('user'))
let page = parseInt(req.nextUrl.searchParams.get('page')!)
let limit = 10
let offset = 0

Expand All @@ -13,18 +13,6 @@ export async function GET(req: NextRequest, res: NextResponse) {
offset = (page + 1) * limit
}

// const feed = await sql`
// SELECT *
// FROM BlogPosts
// WHERE authorid IN (
// SELECT followeeid
// FROM Follows
// WHERE followerid = ${user_id}
// )
// ORDER BY creationdate DESC
// LIMIT ${limit} OFFSET ${offset}
// `
// const feed = await sql('SELECT * FROM BlogPosts WHERE authorid IN (SELECT followeeid FROM Follows WHERE followerid = $1) ORDER BY creationdate DESC LIMIT $2 OFFSET $3', [user_id, limit, offset])
const userFollowings = await postgres.follow.findMany({
select: {
followingId: true,
Expand Down Expand Up @@ -56,46 +44,16 @@ export async function GET(req: NextRequest, res: NextResponse) {
tags: true,
}
})
//execute algorithm to determine the end of the feed
// const feedLength = await sql`
// SELECT COUNT(*) AS feedlength
// FROM BlogPosts
// WHERE authorid IN (
// SELECT followeeid
// FROM Follows
// WHERE followerid = ${user_id}
// )
// `;
const feedLength = postgres.post.count({

// check if there are more posts
const feedLength = await postgres.post.count({
where: {
authorId: {
in: userFollowings.map((user) => user.followingId),
},
},
})

//execute a query to fetch the number of comments of the posts
// const postComments = await sql`
// SELECT blogpostid, COUNT(*) AS commentscount
// FROM Comments
// GROUP BY blogpostid
// `;

// const author = await sql`
// SELECT *
// FROM Users
// WHERE userid IN (
// SELECT authorid
// FROM BlogPosts
// WHERE authorid IN (
// SELECT followeeid
// FROM Follows
// WHERE followerid = ${user_id}
// )
// )
// `


const popular = await postgres.post.findMany({
orderBy: {
views: 'desc',
Expand Down
4 changes: 2 additions & 2 deletions app/api/follow/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import postgres from "@/lib/postgres";

export async function GET(request: NextRequest) {
try{
const followeeId = request.nextUrl.searchParams.get("followeeId");
const followerId = request.nextUrl.searchParams.get("followerId");
const followeeId = Number(request.nextUrl.searchParams.get("followeeId"));
const followerId = Number(request.nextUrl.searchParams.get("followerId"));

if (!followeeId || !followerId) {
return new Response("followeeId and followerId are required query parameters", { status: 400 });
Expand Down
4 changes: 2 additions & 2 deletions app/api/follow/tag/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import postgres from "@/lib/postgres"
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest){
export async function GET(request: NextRequest){
const tagid = Number(request.nextUrl.searchParams.get("tagId"))
const userid = request.nextUrl.searchParams.get("userId")
const userid = Number(request.nextUrl.searchParams.get("userId"))

try {
if (!tagid || !userid){
Expand Down
2 changes: 1 addition & 1 deletion app/api/posts/validate-url/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import postgres from "@/lib/postgres";
export async function GET(request: NextRequest) {
try {
const url = request.nextUrl.searchParams.get("url");
const authorId = request.nextUrl.searchParams.get("authorId")?.toString();
const authorId = Number(request.nextUrl.searchParams.get("author"));

if (!url) {
return new Response("url is required query parameter", { status: 400 });
Expand Down
17 changes: 17 additions & 0 deletions app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { revalidatePath } from 'next/cache'
import { NextRequest } from 'next/server'

export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')

if (path) {
revalidatePath(path)
return Response.json({ revalidated: true, now: Date.now() })
}

return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',
})
}
20 changes: 10 additions & 10 deletions app/api/users/[username]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { NextResponse } from 'next/server';

export async function GET(req: Request, { params }: { params: { username: string }}) {
try {
// Get the 'slug' route parameter from the request object
const username = params.username;

if (username === undefined || username === null) {
Expand All @@ -14,22 +13,23 @@ export async function GET(req: Request, { params }: { params: { username: string
const result = await postgres.user.findFirst({
include: {
posts: true,
Followers: true,
Following: true,
Followers: {
include: {
following: true
}
},
Following: {
include: {
follower: true
}
},
notifications: true,
},
where: {
OR: [{username: username}, {name: username}]
}
})

const posts = await postgres.post.findMany({
where: {
authorId: result?.id,
visibility: "public",
}
})

if (!result) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
Expand Down
6 changes: 3 additions & 3 deletions app/api/users/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
try {
const id = request.nextUrl.searchParams.get("id");
const id = Number(request.nextUrl.searchParams.get("id"));
if (id) {
const user = await postgres.user.findUnique({
where: {
Expand All @@ -13,8 +13,8 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ user: user }, { status: 200});
} else {
const result = await postgres.user.findMany()

const user = result;
const user = result;
return NextResponse.json({ user }, { status: 200});
}
// Execute a query to fetch all table name

Expand Down
25 changes: 16 additions & 9 deletions app/api/users/top/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from "next/server";
// api to execute the top users query by followers and return the result
export async function GET(request: NextRequest) {
try {
const userid = request.nextUrl.searchParams.get("user")?.toString();
const userid = Number(request.nextUrl.searchParams.get("user"));

// execute the query to fetch the top 5 users by followers where the user is not following them and dont display the user itself

Expand All @@ -20,6 +20,15 @@ export async function GET(request: NextRequest) {
// LIMIT 5
// `;
// const users = await sql('SELECT * FROM Users WHERE userid NOT IN (SELECT followeeid FROM Follows WHERE followerid = $1) AND userid <> $1 ORDER BY (SELECT COUNT(*) FROM Follows WHERE followeeid = Users.userid) DESC LIMIT 5', [userid])
const userFollowings = await postgres.follow.findMany({
select: {
followingId: true,
},
where: {
followerId: userid,
},
});

const topUsers = await postgres.user.findMany({
include: {
Followers: true,
Expand All @@ -28,15 +37,13 @@ export async function GET(request: NextRequest) {
},
take: 5,
where: {
Followers: {
some: {
followerId: {
not: userid, // Replace with the user's ID
}, // Replace with the user's ID
},
},
id: {
not: userid, // Replace with the user's ID
not: userid,
},
Following: {
none: {
followerId: userid,
},
},
},
orderBy: {
Expand Down
10 changes: 5 additions & 5 deletions app/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@ export const config = {
await postgres.user.create({
data: {
username: username,
name: name || '',
email: email || '',
bio: bio || '',
name: name,
email: email,
bio: bio,
githubprofile: githubProfileURL,
location: location || '',
location: location,
image: avatar_url,
password: ''
password: "github"
}
})

Expand Down
2 changes: 1 addition & 1 deletion components/feed/featured/featured-dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function FeaturedDev(
setIsFollowingLoading(newLoadingStates);

try {
const followerId = (await getSessionUser()).id;
const followerId = (await getSessionUser())?.id;

await fetch(`/api/follow?followeeId=${followeeId}&followerId=${followerId}`, {
method: "GET",
Expand Down
Loading

0 comments on commit 810011d

Please sign in to comment.