Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(#6): created blog posts page 💅 #15

Merged
merged 2 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,274 changes: 1,274 additions & 0 deletions 6-create-blog-posts-page.patch

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions drizzle.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default {
dbCredentials: {
connectionString: env.DATABASE_URL,
},
verbose: true,
driver: "pg",
tablesFilter: ["kujo205-blog_*"],
out: "./src/server/db",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.49.3",
"react-intersection-observer": "^9.10.2",
"rehype-code-titles": "^1.2.0",
"rehype-prism-plus": "^2.0.0",
"remark-gfm": "3.0.0",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 58 additions & 0 deletions src/app/posts/_components/BlogPostCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { type TBlogPost, type TTag } from "@/server/db/schema";
import { Icons } from "@/components/icons";
import Link from "next/link";
const PLACEHOLDER_IMAGE_URL = "/placeholder-blogpost-img.png";

export function BlogPostCard({
post,
}: {
post: Omit<TBlogPost, "content"> & { tags: TTag[] };
}) {
const updatedAt = new Date(post.updatedAt!).toLocaleDateString();

return (
<Link href={`/posts/${post.id}`}>
<article className="max-w-[512px] overflow-hidden rounded-2xl border border-gray-500 bg-slate-50">
<img
src={post.thumbnail ?? PLACEHOLDER_IMAGE_URL}
className="h-[280px] w-full object-cover"
/>
<div className="flex flex-col gap-4 overflow-hidden p-4">
<div>
<h1 className="text-2xl font-bold text-violet-600">{post.title}</h1>
{/* actions */}
<div></div>
</div>
<p>{post.description}</p>
<div className="flex flex-wrap gap-2">
{post.tags.map((tag) => (
<span
key={tag.id}
className="text-purple-accent border-purple-accent rounded-[12px] border px-5 py-2"
>
{tag.name}
</span>
))}
</div>
{/* meta information */}
<div className="flex justify-between">
<span className="text-gray-neutral flex gap-2">
<Icons.Eye />
{post.watched}
</span>
<span>
Last edited:
<span className="font-bold text-pink-500">
{formatISOString(updatedAt)}
</span>
</span>
</div>
</div>
</article>
</Link>
);
}

function formatISOString(date: string) {
return ` ${new Date(date).toLocaleDateString().toString()}`;
}
31 changes: 0 additions & 31 deletions src/app/posts/_components/PostSearch/SortOptionsSelect.tsx

This file was deleted.

4 changes: 1 addition & 3 deletions src/app/posts/_components/PostSearch/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search } from "lucide-react";
import { SortOptionsSelect } from "./SortOptionsSelect";
import { useMemo, type SetStateAction, type Dispatch } from "react";
import { api } from "@/trpc/react";

Expand Down Expand Up @@ -41,7 +40,7 @@ function PostSearch({
}

return (
<div className="flex max-w-[1080px] flex-col gap-[16px] 0:w-full">
<div className="flex max-w-[1080px] flex-col gap-4 py-4 0:w-full">
{/* search with select */}
<div className=" flex justify-between rounded bg-gradient-to-r from-[#4F3ABA] to-[#D94E68] p-[16px] max-sm:flex-col max-sm:gap-[16px]">
<div className="flex w-full flex-[.55] gap-[8px]">
Expand All @@ -53,7 +52,6 @@ function PostSearch({
<Search onChange={() => onSearchBtnClick()} />
</Button>
</div>
<SortOptionsSelect className="w-full flex-[.2]" />
</div>

{/* tags */}
Expand Down
55 changes: 33 additions & 22 deletions src/app/posts/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"use client";

import { useInView } from "react-intersection-observer";
import { BlogPostCard } from "./_components/BlogPostCard";
import { api } from "@/trpc/react";
import { PostSearch } from "./_components/PostSearch";
import { useState } from "react";
import { useDebounce } from "use-debounce";
const PAGE_SIZE = 9;

export default function Page() {
const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
Expand All @@ -13,26 +15,32 @@ export default function Page() {
function handleSearchValueChange(value: string) {
setSearch(value);
}
const {
data: postsResponse,
refetch,
fetchNextPage,
} = api.post.getPosts.useInfiniteQuery(
{
pageSize: PAGE_SIZE,
search: debouncedSearch,
tagIds: selectedTagIds,
},
{
initialCursor: 0,
getNextPageParam: (lastPage) => {
const lastPost = lastPage.posts[lastPage.posts.length - 1];
return lastPost?.id;
},
},
);

const { data: postsResponse, refetch } = api.post.getPosts.useInfiniteQuery({
page: 0,
pageSize: 5,
search: debouncedSearch,
tagIds: selectedTagIds,
const { ref } = useInView({
/* Optional options */
threshold: 0,
onChange: () => {
fetchNextPage();
},
});
//
// const { data: postsResponse, refetch } = api.post.getPosts.useQuery(
// {
// cursor: 0,
// page: 0,
// pageSize: 5,
// search: debouncedSearch,
// tagIds: selectedTagIds,
// },
// // {
// // getNextPageParam: (lastPage) =>
// // },
// );

return (
<main className="flex flex-col items-center px-4 py-16">
Expand All @@ -44,9 +52,12 @@ export default function Page() {
setSelectedTagIds={setSelectedTagIds}
selectedTagIds={selectedTagIds}
/>
{JSON.stringify(postsResponse, undefined, 2)}
{/*{postsResponse.left}*/}
<h1>Working on it cap</h1>
<div className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{postsResponse?.pages.map((page) =>
page.posts.map((post) => <BlogPostCard key={post.id} post={post} />),
)}
<div ref={ref} />
</div>
</main>
);
}
2 changes: 2 additions & 0 deletions src/components/icons/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
MousePointerClick,
PlusIcon,
Search,
Eye,
} from "lucide-react";

export const Icons = {
Expand All @@ -13,4 +14,5 @@ export const Icons = {
MousePointerClick,
Delete,
PlusIcon,
Eye,
};
6 changes: 2 additions & 4 deletions src/server/api/routers/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,21 @@ export const postRouter = createTRPCRouter({
z.object({
cursor: z.number().optional(),
search: z.string(),
page: z.number(),
pageSize: z.number(),
tagIds: z.array(z.number()),
}),
)
.query(async ({ input, ctx }) => {
const { posts, pagesLeft } = await PostService.getSortedPosts(
const { posts } = await PostService.getSortedPosts(
input.tagIds,
input.page,
input.search,
input.pageSize,
input.cursor!,
);

return {
...input,
posts,
left: pagesLeft,
};
}),

Expand Down
57 changes: 21 additions & 36 deletions src/server/api/services/Post.service.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,48 @@
import { db } from "../../db";
import { ilike, or } from "drizzle-orm";
import { blogPosts } from "../../db/schema";
import { ilike, or, and, inArray, gt } from "drizzle-orm";
import { blogPosts, tagsToBlogPosts } from "../../db/schema";

class PostService {
public async getSortedPosts(
tagIds: number[],
page: number,
search: string,
pageSize: number,
cursor: number,
) {
const posts = await db.query.blogPosts.findMany({
where: or(
ilike(blogPosts.title, `%${search}%`),
ilike(blogPosts.content, `%${search}%`),
ilike(blogPosts.description, `%${search}%`),
limit: pageSize,
where: and(
cursor ? gt(blogPosts.id, cursor) : undefined,
or(
ilike(blogPosts.title, `%${search}%`),
ilike(blogPosts.content, `%${search}%`),
ilike(blogPosts.description, `%${search}%`),
),
),
columns: {
content: false,
},
with: {
tagsToBlogPosts: {
where:
tagIds.length > 0
? inArray(tagsToBlogPosts.tagId, tagIds)
: undefined,
with: {
blogPostTags: true,
},
},
},
});

const postInputTagsSize = tagIds.length;

const postsSortedByTags = posts
.filter((post) => {
const tagIds = post.tagsToBlogPosts.map((tag) => tag.tagId);
if (postInputTagsSize === 0) return true;

return tagIds.some((tagId) => tagIds.includes(tagId));
})
.sort((postA, postB) => {
const aTagIds = postA.tagsToBlogPosts.map((tag) => tag.tagId);
const bTagIds = postB.tagsToBlogPosts.map((tag) => tag.tagId);

return (
this.countHowManyMatches(bTagIds, tagIds) -
this.countHowManyMatches(aTagIds, tagIds)
);

return 1;
});

const postsSlicedByPage = postsSortedByTags.slice(
page * pageSize,
(page + 1) * pageSize,
);

const pagesLeft = Math.ceil(postsSortedByTags.length / pageSize) - page;
const mappedPosts = posts.map((post) => ({
...post,
tagsToBlogPosts: undefined,
tags: post.tagsToBlogPosts.map((tag) => tag.blogPostTags),
}));

return {
posts: postsSlicedByPage,
pagesLeft,
posts: mappedPosts,
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/server/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export const connection = postgres(env.DATABASE_URL, {
prepare: false,
});

export const db = drizzle(connection, { schema });
export const db = drizzle(connection, { schema, logger: true });
1 change: 1 addition & 0 deletions src/server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,4 @@ export const messages = pgTable("message", {

export type UserRole = typeof users.$inferSelect.role;
export type TTag = typeof blogPostTags.$inferSelect;
export type TBlogPost = typeof blogPosts.$inferSelect;
2 changes: 2 additions & 0 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ const config = {
foreground: "hsl(var(--card-foreground))",
},
"font-accent": "var(--text-accent)",
"purple-accent": "#5D4B74",
"gray-neutral": "#7F7F7F",
},
borderRadius: {
lg: "var(--radius)",
Expand Down