@@ -4,6 +4,7 @@ import { sql } from "@vercel/postgres";
44import { unstable_noStore as noStore , revalidatePath } from "next/cache" ;
55import { redirect } from "next/navigation" ;
66import camelcaseKeys from "camelcase-keys" ;
7+ import { auth } from "@/auth" ;
78
89/**
910 * 게시물을 생성합니다.
@@ -19,41 +20,42 @@ export async function postPost({
1920} ) {
2021 noStore ( ) ;
2122
22- try {
23- await sql `
24- CREATE TABLE IF NOT EXISTS posts (
25- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
26- index SERIAL,
27- title TEXT NOT NULL,
28- content TEXT NOT NULL,
29- tags TEXT[] DEFAULT '{}',
30- comments UUID[] DEFAULT '{}',
31- created_at DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
32- updated_at DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
33- deleted_at DATE DEFAULT NULL,
34- status TEXT NOT NULL DEFAULT 'published',
35- likes INT DEFAULT 0,
36- views INT DEFAULT 0
37- )
38- ` ;
23+ // 인증 체크
24+ const session = await auth ( ) ;
25+ if ( ! session ?. user ) {
26+ throw new Error ( "Unauthorized: 로그인이 필요합니다." ) ;
27+ }
3928
40- await sql . query (
41- `
42- INSERT INTO posts (title, content)
43- VALUES ($1, $2)
44- ` ,
45- [ title , markdownValue ]
46- ) ;
29+ // 입력 검증
30+ if ( ! title || ! title . trim ( ) ) {
31+ throw new Error ( "제목을 입력해주세요." ) ;
32+ }
33+ if ( ! markdownValue || ! markdownValue . trim ( ) ) {
34+ throw new Error ( "내용을 입력해주세요." ) ;
35+ }
4736
48- const { rows } =
49- await sql `SELECT index FROM posts ORDER BY index DESC LIMIT 1` ;
37+ try {
38+ const { rows } = await sql `
39+ INSERT INTO posts (title, content)
40+ VALUES (${ title . trim ( ) } , ${ markdownValue . trim ( ) } )
41+ RETURNING index
42+ ` ;
5043
51- revalidatePath ( `/posts/${ rows [ 0 ] . index } ` ) ;
52- redirect ( `/posts/${ rows [ 0 ] . index } ` ) ;
44+ if ( ! rows [ 0 ] ?. index ) {
45+ throw new Error ( "게시물 생성에 실패했습니다." ) ;
46+ }
5347
54- return camelcaseKeys ( rows [ 0 ] , { deep : true } ) as IPost ;
48+ const postIndex = rows [ 0 ] . index ;
49+ revalidatePath ( `/posts/${ postIndex } ` ) ;
50+ revalidatePath ( "/posts" ) ;
51+ revalidatePath ( "/" ) ;
52+ redirect ( `/posts/${ postIndex } ` ) ;
5553 } catch ( error ) {
5654 console . error ( "Database Error:" , error ) ;
57- throw new Error ( "Failed to fetch recent posts data." ) ;
55+ throw new Error (
56+ error instanceof Error
57+ ? error . message
58+ : "게시물 생성 중 오류가 발생했습니다."
59+ ) ;
5860 }
5961}
0 commit comments