1- //Comment section
1+ // Vercel serverless function
2+ import { kv } from '@vercel/kv' ;
3+
4+ export default async function handler ( req , res ) {
5+ const { method } = req ;
6+
7+ if ( method === 'GET' ) {
8+ const slug = req . query . slug ;
9+ if ( ! slug ) {
10+ return res . status ( 400 ) . json ( { error : "Missing slug" } ) ;
11+ }
12+ const comments = await kv . get ( `comments:${ slug } ` ) || [ ] ;
13+ return res . status ( 200 ) . json ( comments ) ;
14+ }
15+
16+ if ( method === 'POST' ) {
17+ const { slug, text } = req . body ;
18+ if ( ! slug || ! text ) {
19+ return res . status ( 400 ) . json ( { error : "Missing slug or text" } ) ;
20+ }
21+ const comments = await kv . get ( `comments:${ slug } ` ) || [ ] ;
22+ const newComment = { text, timestamp : Date . now ( ) } ;
23+ comments . push ( newComment ) ;
24+ await kv . set ( `comments:${ slug } ` , comments ) ;
25+ return res . status ( 201 ) . json ( newComment ) ;
26+ }
27+
28+ res . setHeader ( 'Allow' , [ 'GET' , 'POST' ] ) ;
29+ res . status ( 405 ) . end ( `Method ${ method } Not Allowed` ) ;
30+ }
31+
32+ document . addEventListener ( "DOMContentLoaded" , ( ) => {
33+ const slug = new URLSearchParams ( window . location . search ) . get ( 'id' ) ;
34+ if ( ! slug ) return ;
35+
36+ const commentsList = document . getElementById ( "comments-list" ) ;
37+ const form = document . getElementById ( "comment-form" ) ;
38+
39+ // Load existing comments
40+ fetch ( `/api/comments?slug=${ slug } ` )
41+ . then ( res => res . json ( ) )
42+ . then ( comments => {
43+ comments . forEach ( comment => {
44+ const p = document . createElement ( "p" ) ;
45+ p . textContent = comment . text ;
46+ commentsList . appendChild ( p ) ;
47+ } ) ;
48+ } )
49+ . catch ( err => {
50+ console . error ( "Failed to load comments" , err ) ;
51+ } ) ;
52+
53+ // Submit new comment
54+ form . addEventListener ( "submit" , ( e ) => {
55+ e . preventDefault ( ) ;
56+ const text = document . getElementById ( "comment-text" ) . value . trim ( ) ;
57+ if ( text . length === 0 ) return ;
58+
59+ fetch ( '/api/comments' , {
60+ method : 'POST' ,
61+ headers : {
62+ 'Content-Type' : 'application/json'
63+ } ,
64+ body : JSON . stringify ( { slug, text } )
65+ } )
66+ . then ( res => res . json ( ) )
67+ . then ( newComment => {
68+ const p = document . createElement ( "p" ) ;
69+ p . textContent = newComment . text ;
70+ commentsList . appendChild ( p ) ;
71+ document . getElementById ( "comment-text" ) . value = "" ;
72+ } )
73+ . catch ( err => {
74+ console . error ( "Failed to post comment" , err ) ;
75+ } ) ;
76+ } ) ;
77+ } ) ;
0 commit comments