Skip to content

Commit

Permalink
feat: refactor post and comment handling to use Prisma for data manag…
Browse files Browse the repository at this point in the history
…ement
  • Loading branch information
ifalfahri committed Jan 11, 2025
1 parent 41854bc commit 05c1c85
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 41 deletions.
25 changes: 25 additions & 0 deletions prisma/migrations/20250111135524_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- CreateTable
CREATE TABLE "Post" (
"id" TEXT NOT NULL,
"from" TEXT NOT NULL DEFAULT 'Anonim',
"to" TEXT NOT NULL,
"message" TEXT NOT NULL,
"timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"loveCount" INTEGER NOT NULL DEFAULT 0,

CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "Comment" (
"id" TEXT NOT NULL,
"from" TEXT NOT NULL DEFAULT 'Anonim',
"text" TEXT NOT NULL,
"timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"postId" TEXT NOT NULL,

CONSTRAINT "Comment_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Comment" ADD CONSTRAINT "Comment_postId_fkey" FOREIGN KEY ("postId") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
5 changes: 3 additions & 2 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ export default function Home() {
const [posts, setPosts] = useState<KeluhPost[]>([]);
const [isNewPostOpen, setIsNewPostOpen] = useState(false);

const loadPosts = () => {
setPosts(getPosts());
const loadPosts = async () => {
const posts = await getPosts();
setPosts(posts);
};

useEffect(() => {
Expand Down
7 changes: 3 additions & 4 deletions src/components/keluh-add.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,19 @@ export function KeluhAdd({
message: '',
});

const handleSubmit = (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();

const newPost: KeluhPost = {
const newPost: Omit<KeluhPost, 'comments'> = {
id: crypto.randomUUID(),
from: formData.from || 'Anonim',
to: formData.to,
message: formData.message,
timestamp: new Date().toISOString(),
loveCount: 0,
comments: [],
};

savePost(newPost);
await savePost(newPost);
setFormData({ from: '', to: '', message: '' });
onOpenChange(false);
onPostCreated();
Expand Down
8 changes: 4 additions & 4 deletions src/components/keluh-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ export function KeluhCard({ post, onUpdate }: KeluhCardProps) {
const [comment, setComment] = useState('');
const [commentFrom, setCommentFrom] = useState('');

const handleLove = (e: React.MouseEvent) => {
const handleLove = async (e: React.MouseEvent) => {
e.stopPropagation();
toggleLove(post.id);
await toggleLove(post.id);
onUpdate();
};

const handleComment = (e: React.FormEvent) => {
const handleComment = async (e: React.FormEvent) => {
e.preventDefault();
if (!comment.trim()) return;

addComment(post.id, {
await addComment(post.id, {
id: crypto.randomUUID(),
from: commentFrom || 'Anonim',
text: comment,
Expand Down
64 changes: 33 additions & 31 deletions src/lib/storage.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,46 @@
import { KeluhPost, Comment } from '@/app/types';
"use server"

const STORAGE_KEY = 'keluh-posts';
import { PrismaClient } from '@prisma/client';

export function getPosts(): KeluhPost[] {
if (typeof window === 'undefined') return [];
const posts = localStorage.getItem(STORAGE_KEY);
return posts ? JSON.parse(posts) : [];
const prisma = new PrismaClient();

export async function getPosts() {
return await prisma.post.findMany({
include: { comments: true },
});
}

export function savePost(post: KeluhPost) {
const posts = getPosts();
posts.unshift(post);
localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
export async function savePost(post) {
const { comments, ...postData } = post;
return await prisma.post.create({
data: postData,
});
}

export function updatePost(updatedPost: KeluhPost) {
const posts = getPosts();
const index = posts.findIndex((post) => post.id === updatedPost.id);
if (index !== -1) {
posts[index] = updatedPost;
localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
}
export async function updatePost(updatedPost) {
return await prisma.post.update({
where: { id: updatedPost.id },
data: updatedPost,
});
}

export function addComment(postId: string, comment: Comment) {
const posts = getPosts();
const post = posts.find((p) => p.id === postId);
if (post) {
post.comments.push(comment);
localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
}
export async function addComment(postId, comment) {
return await prisma.comment.create({
data: {
...comment,
postId,
},
});
}

export function toggleLove(postId: string) {
const posts = getPosts();
const post = posts.find((p) => p.id === postId);
export async function toggleLove(postId) {
const post = await prisma.post.findUnique({
where: { id: postId },
});
if (post) {
post.loveCount += 1;
localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
return post.loveCount;
return await prisma.post.update({
where: { id: postId },
data: { loveCount: post.loveCount + 1 },
});
}
return 0;
}

0 comments on commit 05c1c85

Please sign in to comment.