Skip to content

Commit

Permalink
update routes
Browse files Browse the repository at this point in the history
  • Loading branch information
thebkht committed Oct 30, 2023
1 parent 06abe5f commit 3db7338
Show file tree
Hide file tree
Showing 13 changed files with 190 additions and 204 deletions.
59 changes: 27 additions & 32 deletions app/(Main)/[username]/[url]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

import React, { use, useEffect, useState } from "react"
'use server'
import { getSessionUser } from "@/components/get-session-user"
import { redirect, useRouter } from "next/navigation"
import postgres from "@/lib/postgres"
import Post from "@/components/blog/post"
import PostComment from "@/components/blog/comment"
import MoreFromAuthor from "@/components/blog/more-from-author"
import { cookies } from 'next/headers'
import { incrementPostViews } from "@/components/blog/actions"


export default async function PostView({ params }: { params: { username: string, url: string } }) {
Expand All @@ -22,8 +23,18 @@ export default async function PostView({ params }: { params: { username: string,
}
},
include: {
_count: { select: { comments: true } }
}
_count: { select: { comments: true, savedUsers: true, likes: true } },
author: {
include: {
Followers: true,
Followings: true
}
},
},
orderBy: {
createdAt: "desc"
},
take: 4
},
_count: { select: { posts: true, Followers: true, Followings: true } },
Followers: true,
Expand Down Expand Up @@ -54,7 +65,13 @@ export default async function PostView({ params }: { params: { username: string,
tag: true
}
},
_count: { select: { savedUsers: true, likes: true } }
author: {
include: {
Followers: true,
Followings: true
}
},
_count: { select: { savedUsers: true, likes: true, comments: true } }
}
});
if (!post) redirect("/404");
Expand All @@ -66,34 +83,12 @@ export default async function PostView({ params }: { params: { username: string,
if (post?.visibility !== "public") redirect("/404");
}

// async function handleFollow(followeeId: string) {
// if (status === "authenticated") {
// setIsFollowingLoading(true);
// try {
// const followerId = (await getSessionUser()).userid;
// await fetch(`/api/follow?followeeId=${followeeId}&followerId=${followerId}`, {
// method: "GET",
// });
// } catch (error) {
// console.error(error);
// }
// } else {
// return null;
// }

// }


// if (!isLoaded || !post) {
// 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>
// )
// }
await fetch(`${process.env.DOMAIN}/api/posts/${author?.username}/views/`, {
method: "POST",
body: JSON.stringify({ post: post, author: author }),
});

return (
<>
Expand Down
35 changes: 18 additions & 17 deletions app/(Main)/[username]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ export default async function Page({ params }: {
orderBy: {
createdAt: "desc"
},
include: {
_count: {
select: {
likes: true,
savedUsers: true,
},
},
tags: {
take: 1,
include: {
tag: true,
},
},
},
},
Followers: {
include: {
Expand All @@ -43,28 +57,15 @@ export default async function Page({ params }: {
if (!user) redirect("/404");

const posts = user.posts;
const postComments = await postgres.comment.findMany({
where: {
postId: {
in: posts.map((post: any) => post.id)
}
}
});

posts?.forEach((post: any) => {
postComments?.forEach((comment: any) => {
if (comment.postid === post.postid) {
post.comments = post.comments + 1;
}
}
)
}
)
post.author = user;
})

const followers = user.Followers;
const following = user.Followings;

const sessionUserName = await getSession();
console.log(sessionUserName);
const sessionUserName = await getSessionUser();

return (
<div className="Layout Layout--flowRow-until-md gap-2 lg:gap-6" >
Expand Down
7 changes: 4 additions & 3 deletions app/(Main)/feed/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { fetchTags } from '@/components/feed/get-tags';
import { getSessionUser } from '@/components/get-session-user';
import FeedTabs from '@/components/feed/navbar/navbar';
import { revalidatePath, revalidateTag } from 'next/cache';
import { redirect } from 'next/navigation';

export default async function Feed({
searchParams
Expand All @@ -28,9 +29,9 @@ export default async function Feed({
console.log("Feed before revalidate", feed);
tag ? revalidatePath('/feed?tag='+tag) : revalidatePath('/feed');
console.log("Feed after revalidate", feed);
// if(!session) {
// return redirect('/')
// }
if(!session) {
return redirect('/')
}

const userFollowings = session?.tagfollower;

Expand Down
4 changes: 2 additions & 2 deletions app/(Main)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { redirect } from 'next/navigation';
import dynamic from 'next/dynamic'

export default function Home() {
const { status, update } = useSession();
const { status } = useSession();

const LoadedLanding = dynamic(() => import('@/components/landing/landing'), {
ssr: false,
});

if (status === 'authenticated') {
if (status !== 'unauthenticated') {
redirect('/feed');
}
return <LoadedLanding />;
Expand Down
125 changes: 75 additions & 50 deletions app/api/feed/route.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,84 @@
import postgres from '@/lib/postgres'
import { NextRequest, NextResponse } from 'next/server'

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

const userFollowings = await postgres.follow.findMany({
select: {
followingId: true,
},
where: {
followerId: user_id,
},
})
const feed = await postgres.post.findMany({
where: {
authorId: {
in: userFollowings.map((user) => user.followingId),
export async function POST(req: NextRequest) {
const { page = 0, tag, id } = await req.json()
if (!id) {
return NextResponse.json({ error: 'No user found' }, { status: 500 })
}
if (tag) {
const postTags = await postgres.postTag.findMany({
select: { postId: true },
where: { tag: { name: { equals: tag } } },
});
const postIds = postTags.map((postTag) => postTag.postId);
return fetchFeed({
where: { id: { in: postIds } },
orderBy: { createdAt: "desc" },
take: 5,
skip: page * 5,
include: {
author: {
include: {
Followers: true,
Followings: true,
},
},
},
orderBy: {
createdAt: 'desc',
},
take: limit,
skip: page * limit,
include: {
author: {
include: {
Followers: true,
Followings: true,
}
},
_count: {
select: {
likes: true,
comments: true,
savedUsers: true,
_count: {
select: {
likes: true,
savedUsers: true,
},
},
tags: {
take: 1,
include: {
tag: true,
},
},
},
tags: {
take: 1,
include: {
tag: true,
});
} else {
const following = await postgres.follow.findMany({
select: { followingId: true },
where: { followerId: id },
});
const followingIds = following.map((user) => user.followingId);
return fetchFeed({
where: { authorId: { in: followingIds } },
orderBy: { createdAt: "desc" },
take: 5,
skip: page * 5,
include: {
author: {
include: {
Followers: true,
Followings: true,
},
},
},
}
})
_count: {
select: {
likes: true,
savedUsers: true,
},
},
tags: {
take: 1,
include: {
tag: true,
},
},
},
});
}
}

return NextResponse.json({ feed }, { status: 200 })
const fetchFeed = async (query: any) => {
try {
const feed = await postgres.post.findMany(query);
await new Promise((resolve) => setTimeout(resolve, 750));
return NextResponse.json({ feed: feed}, { status: 200 });
} catch (error) {
return NextResponse.json({ error: error }, { status: 500 });
}
catch (error) {
console.error(error)
return NextResponse.json({ error: 'Something went wrong' }, { status: 500 })
}
}
};
66 changes: 11 additions & 55 deletions app/api/posts/[username]/views/route.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,15 @@
import postgres from "@/lib/postgres";
import { NextRequest, NextResponse } from "next/server";
// pages/api/some-route.ts
import { NextRequest, NextResponse } from 'next/server';
import { incrementPostViews } from '@/components/blog/actions';

export async function POST(
req: NextRequest,
{ params }: { params: { username: string } }
) {
try {
// Get the 'slug' route parameter from the request object
const username = params.username;
const postUrl = req.nextUrl.searchParams.get("url");
export default async function POST(req: NextRequest, res: NextResponse) {
const { post } = await req.json();
const { author } = await req.json();

if (username === undefined || username === null) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
if (postUrl === undefined || postUrl === null) {
return NextResponse.json({ error: "Post not found" }, { status: 404 });
}
const cookie = await incrementPostViews({ post, author });

// Check if the view has already been counted by looking for a cookie
const cookieName = `post_views_${username}_${postUrl}`;
const hasViewed = req.cookies.get(cookieName);
// Set the cookie
res.cookies.set(cookie)

if (!hasViewed) {
// Execute a query to fetch the specific userid by name
const author = await postgres.user.findUnique({
where: {
username: username,
},
select: {
id: true,
},
});
const authorID = author?.id;

await postgres.post.update({
where: {
url: postUrl,
authorId: authorID,
},
data: {
views: {
increment: 1,
},
},
});
// Set a cookie to indicate that the post has been viewed
req.cookies.set(cookieName, "true",)
}

return NextResponse.json({ message: "View added" }, { status: 200 });
} catch (error) {
console.log(error);
return NextResponse.json(
{ error: "Something went wrong" },
{ status: 500 }
);
}
}
return NextResponse.json({ message: 'Post view incremented' }, { status: 200 });
}
Loading

0 comments on commit 3db7338

Please sign in to comment.