Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/yusupovbg/FalseNote
Browse files Browse the repository at this point in the history
  • Loading branch information
thebkht committed Nov 7, 2023
2 parents 535c822 + 3f2415c commit d21baea
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 77 deletions.
12 changes: 4 additions & 8 deletions app/(Main)/feed/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { redirect } from 'next/navigation';
import { fetchFollowingTags } from '@/components/get-following-tags';
import { getSession } from 'next-auth/react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { fetchForYou } from '@/components/feed/get-foryou';
import { getBookmarks } from '@/lib/prisma/session';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { dateFormat } from '@/lib/format-date';
Expand All @@ -25,15 +24,14 @@ export default async function Feed({
searchParams: { [key: string]: string | string[] | undefined }
}) {

const tag = typeof searchParams.tag === 'string' ? searchParams.tag : undefined
const feed = await fetchFeed({ page: 0, tag });
const tab = typeof searchParams.tab === 'string' ? searchParams.tab : undefined
const feed = await fetchFeed({ page: 0, tab });
const session = await getSessionUser();

const topData = await fetchUsers({ id: session?.id })
const topUsers = topData?.topUsers;
const popularTags = await fetchTags();

console.log(topData)
if (!session) {
return redirect('/')
}
Expand All @@ -42,14 +40,12 @@ export default async function Feed({

const { bookmarks, bookmarksCount } = await getBookmarks({ id: session?.id })

const recommendedPosts = await fetchForYou({ page: 0 })

return (
<>
<main className="flex flex-col items-center justify-between feed xl:px-8">
<div className="md:flex lg:flex-nowrap flex-wrap md:mx-[-16px] w-full xl:gap-8 md:gap-4">
<div className="md:my-4 w-full lg:w-2/3">
{userFollowings.length !== 0 && <FeedTabs tabs={userFollowings} activeTab={tag} />}
<FeedTabs tabs={userFollowings} activeTab={tab} />
<div className="pt-10">
{!feed || feed.length === 0 ? (
<div className="w-full max-h-screen my-auto flex justify-center items-center bg-background">
Expand All @@ -59,7 +55,7 @@ export default async function Feed({
</div>
</div>
) : (
<InfinitiveScrollFeed initialFeed={feed} tag={tag} session={session} />
<InfinitiveScrollFeed initialFeed={feed} tag={tab} session={session} />
)}
</div>
</div>
Expand Down
6 changes: 3 additions & 3 deletions components/feed/get-feed.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getFeed } from "@/lib/prisma/feed";

export const fetchFeed = async ({ page = 0, tag }: { page?: number, tag?: string | undefined }) => {
const result = await getFeed({ page, tag });

export const fetchFeed = async ({ page = 0, tab }: { page?: number, tab?: string | undefined }) => {
const result = await getFeed({ page, tab });
console.log(result, 'result')
return result?.feed;
}
9 changes: 6 additions & 3 deletions components/feed/get-foryou.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { getForYou } from "@/lib/prisma/feed";

export const fetchForYou = async ({ page = 0 }: { page?: number }) => {
// const result = await getForYou({ page, tag });
const result = await getForYou({ page });

// return result?.feed;
}
return result?.feed;
}

9 changes: 7 additions & 2 deletions components/feed/navbar/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { useInView } from "react-intersection-observer";


export default function FeedTabs({ tabs, activeTab = 'following', children }: { tabs: any, activeTab?: string, children?: React.ReactNode }) {
export default function FeedTabs({ tabs, activeTab = 'foryou', children }: { tabs: any, activeTab?: string, children?: React.ReactNode }) {
const [firstTab, inFView] = useInView();
const [lastTab, inLView] = useInView();

Expand All @@ -26,13 +26,18 @@ export default function FeedTabs({ tabs, activeTab = 'following', children }: {
<ScrollArea className="w-full py-2">
<TabsList className="bg-transparent gap-2">
<Link href={`/feed`}>
<TabsTrigger value="foryou" ref={firstTab} className="bg-muted data-[state=active]:border data-[state=active]:border-foreground">
For You
</TabsTrigger>
</Link>
<Link href={`/feed?tab=following`}>
<TabsTrigger value="following" ref={firstTab} className="bg-muted data-[state=active]:border data-[state=active]:border-foreground">
Following
</TabsTrigger>
</Link>
{tabs?.map((item: any, index: number) => (

<Link href={`/feed?tag=${item.tag.name}`} key={item.tag.id}>
<Link href={`/feed?tab=${item.tag.name}`} key={item.tag.id}>
<TabsTrigger value={item.tag.name} className="bg-muted data-[state=active]:border data-[state=active]:border-foreground capitalize">

{item.tag.name.replace(/-/g, " ")}
Expand Down
164 changes: 103 additions & 61 deletions lib/prisma/feed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,78 @@
import { getSessionUser } from "@/components/get-session-user";
import postgres from "../postgres";
import { getBookmarks, getHistory, getLikes } from "./session";
import { Like } from "@prisma/client";

export const getForYou = async ({ page = 0 }: { page?: number }) => {
const user = await getSessionUser();
if (!user) {
return null;
}
const { id } = user;

//get user's interests
const { likes: userLikes } = await getLikes({id});
const { bookmarks: userBookmarks } = await getBookmarks({id});
const { history: userHistory } = await getHistory({id});

// Fetch the tags of the posts in parallel
const tags = await postgres.postTag.findMany({
where: {
OR: [
{ postId: { in: userLikes.map((like: Like) => like.postId) } },
{ postId: { in: userBookmarks.map((bookmark: any) => bookmark.postId) } },
{ postId: { in: userHistory.map((history: any) => history.postId) } },
]
},
select: {
tagId: true,
},
});
console.log(tags.length, 'tags')

const baseQuery = {
orderBy: { createdAt: "desc" },
take: 5,
skip: page * 5,
include: {
author: true,
savedUsers: true,
_count: {
select: {
likes: true,
savedUsers: true,
},
},
tags: {
take: 1,
include: {
tag: true,
},
},
},
};

// Count the occurrences of each tag
const tagCounts = tags.reduce((counts, tag) => {
counts[tag.tagId] = (counts[tag.tagId] || 0) + 1;
return counts;
}, {} as Record<string, number>);

// Sort the tags by their count in descending order
const sortedTagIds = Object.entries(tagCounts).sort((a, b) => b[1] - a[1]).map(([tagId]) => Number(tagId));

// Fetch the posts that have the tags of the user's main interests
console.log(sortedTagIds, 'sortedTagIds')
const posts = await postgres.post.findMany({
where: { tags: { some: { tagId: { in: sortedTagIds.slice(0, 5) } } } },
select: { id: true },
});
console.log(posts.length, 'for you posts')
return fetchFeed({
where: { id: { in: posts.map((post) => post.id) }, visibility: "public" },
...baseQuery,
});
};

const fetchFeed = async (query: any) => {
try {
Expand All @@ -10,13 +83,15 @@ const fetchFeed = async (query: any) => {
}
};

export const getFeed = async ({ page = 0, tag }: { page?: number; tag?: string | undefined }) => {
export const getFeed = async ({ page = 0, tab }: { page?: number; tab?: string | undefined }) => {
const user = await getSessionUser();
if (!user) {
return null;
}
const { id } = user;

console.log(tab, 'tab')

const baseQuery = {
orderBy: { createdAt: "desc" },
take: 5,
Expand All @@ -38,72 +113,39 @@ export const getFeed = async ({ page = 0, tag }: { page?: number; tag?: string |
},
},
};
if (!tab) {
return await getForYou({ page });
}

if (tag) {
if (tab) {
if (tab == "following") {
const following = await postgres.follow.findMany({
select: { followingId: true },
where: { followerId: id },
});
const followingIds = following.map((user) => user.followingId);
return fetchFeed({
...baseQuery,
where: { authorId: { in: followingIds }, visibility: "public" },
include: {
...baseQuery.include,
author: {
include: {
Followers: true,
Followings: true,
},
},
},
});
}
const postTags = await postgres.postTag.findMany({
select: { postId: true },
where: { tag: { name: { equals: tag } } },
where: { tag: { name: { equals: tab } } },
});
const postIds = postTags.map((postTag) => postTag.postId);
return fetchFeed({
...baseQuery,
where: { id: { in: postIds }, visibility: "public" },
});
} else {
const following = await postgres.follow.findMany({
select: { followingId: true },
where: { followerId: id },
});
const followingIds = following.map((user) => user.followingId);
return fetchFeed({
...baseQuery,
where: { authorId: { in: followingIds }, visibility: "public" },
include: {
...baseQuery.include,
author: {
include: {
Followers: true,
Followings: true,
},
},
},
});
}
};

//fetch recommended posts according to user's interests (likes, bookmarks, reading history)
// export const getForYou = async ({ page = 0, tag }: { page?: number; tag?: string | undefined }) => {
// const user = await getSessionUser();
// if (!user) {
// return null;
// }
// const { id } = user;

// const baseQuery = {
// orderBy: { createdAt: "desc" },
// take: 5,
// skip: page * 5,
// include: {
// author: true,
// _count: {
// select: {
// likes: true,
// savedUsers: true,
// },
// },
// tags: {
// take: 1,
// include: {
// tag: true,
// },
// },
// },
// };

// //get user's interests
// const userLikes = await getLikes({id});
// const userBookmarks = await getBookmarks({id});
// const userHistory = await getHistory({id});


// }
}
};

0 comments on commit d21baea

Please sign in to comment.