Skip to content

Commit

Permalink
add edit post
Browse files Browse the repository at this point in the history
  • Loading branch information
miicolas committed Aug 27, 2024
1 parent d08c069 commit 31ff80d
Show file tree
Hide file tree
Showing 5 changed files with 250 additions and 10 deletions.
58 changes: 58 additions & 0 deletions src/app/api/post/editPost/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import getSession from "@/lib/session";

export async function POST(req: NextRequest) {
const { title, description, content, slug, date, isDraft } = await req.json();

const session = await getSession();

if (!session?.user?.isAdmin) {
return NextResponse.json(
{ message: "You are not authorized to create a post!" },
{ status: 401 }
);
}

try {
const id_post = await prisma.posts.findFirst({
where: {
slug,
},
});

if (!id_post) {
return NextResponse.json({ message: "Post not found!" }, { status: 404 });
}

await prisma.posts.update({
where: {
id: id_post.id,
},
data: {
title,
description,
slug,
date,
content,
isDraft,
},
});

return NextResponse.json(
{ message: "Post updated successfully!" },
{ status: 200 }
);
} catch (error) {
console.error(error);
return NextResponse.json(
{ message: "Failed to update post!" },
{ status: 500 }
);
}

return NextResponse.json(
{ message: "Post updated successfully!" },
{ status: 201 }
);
}
14 changes: 8 additions & 6 deletions src/app/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ export default async function Post({ params }: { params: { slug: string } }) {
<main className="py-5">
<Button asChild>
<Link href="/blog" className="flex items-center gap-2">

<ArrowLeft />
Back to Blog</Link>
<ArrowLeft />
Back to Blog
</Link>
</Button>
<section className="py-10">
<h1>{post?.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post?.content || "" }} />
<p>{post?.date}</p>
<h1 className="text-2xl font-bold">{post?.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post?.content || "" }} className="mt-5" />
<p className="text-sm text-gray-500 mt-5" >
{post?.date}
</p>
<p>{post?.isDraft}</p>
</section>
</main>
Expand Down
2 changes: 1 addition & 1 deletion src/app/blog/create/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CreatePostForm } from "@/components/forms/createPostForm";
import { CreatePostForm } from "@/components/forms/PostForm";
import Header from "@/components/layout/header";
import getSession from "@/lib/session";
import { Session } from "@/lib/types";
Expand Down
28 changes: 28 additions & 0 deletions src/app/blog/edit/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { EditPostForm } from "@/components/forms/PostForm";
import Header from "@/components/layout/header";
import getSession from "@/lib/session";
import { Session } from "@/lib/types";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";

export default async function CreatePost({params}: {params: {slug: string}}) {
const session: Session = await getSession();
if (!session?.user?.isAdmin) {
redirect("/blog");
}

const post = await prisma.posts.findFirst({
where: {
slug: params.slug,
},
});

return (
<>
<Header />
<main>
<EditPostForm post={post!} />
</main>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import RichTextEditor from "@/components/text-editor";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
Expand Down Expand Up @@ -62,7 +60,7 @@ export function CreatePostForm() {
});

const data = await response.json();

if (response.ok) {
toast.success("Post created successfully");
} else {
Expand Down Expand Up @@ -159,3 +157,157 @@ export function CreatePostForm() {
</Form>
);
}

const editorStyles = z.object({
title: z.string().min(1, { message: "Title is required" }),
description: z.string().min(1, { message: "Description is required" }),
content: z.string().min(1, { message: "Content is required" }),
slug: z.string().min(1, { message: "Slug is required" }),
date: z.string().min(1, { message: "Date is required" }),
isDraft: z.boolean().optional(),
});

type EditorProps = {
post: {
title: string;
description: string;
content: string;
slug: string;
date: string;
isDraft: boolean;
};
};

export function EditPostForm({ post }: EditorProps) {
const router = useRouter();

const form = useForm<z.infer<typeof editorStyles>>({
resolver: zodResolver(createPostSchema),
defaultValues: {
isDraft: post.isDraft,
title: post.title,
description: post.description,
content: post.content,
slug: post.slug,
date: post.date,
},
});

const onSubmit = async (values: z.infer<typeof editorStyles>) => {
console.log(values, "values");
const { title, description, content, slug, date, isDraft } = values;
console.log(title, description, content, slug, date, isDraft, "values");

try {
const editPost = async () => {
const response = await fetch("/api/post/editPost", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title,
description,
content,
slug,
date,
isDraft,
}),
});

const data = await response.json();

if (response.ok) {
toast.success("Post updated successfully");
} else {
toast.error("Post update failed");
}
return data;
};

await editPost();
} catch (error) {
console.error(error);
} finally {
router.push("/blog");
router.refresh();
}
};

return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<Input {...field} />
<FormMessage {...field} />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<Textarea {...field} />
<FormMessage {...field} />
</FormItem>
)}
/>
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormLabel>Content</FormLabel>
<RichTextEditor {...field} {...field} />
<FormMessage {...field} />
</FormItem>
)}
/>
<FormField
control={form.control}
name="slug"
render={({ field }) => (
<FormItem>
<FormLabel>Slug</FormLabel>
<Input {...field} />
<FormMessage {...field} />
</FormItem>
)}
/>
<FormField
control={form.control}
name="date"
render={({ field }) => (
<FormItem>
<FormLabel>Date</FormLabel>
<Input {...field} />
<FormMessage {...field} />
</FormItem>
)}
/>
<FormField
control={form.control}
name="isDraft"
render={({ field }) => (
<FormItem>
<FormLabel>Is Draft</FormLabel>
<Switch
id="isDraft"
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
);
}

0 comments on commit 31ff80d

Please sign in to comment.