From 02f94fb09d4d9a772df9e9bd5911ec2af020f77c Mon Sep 17 00:00:00 2001 From: multipleof4 Date: Thu, 2 Oct 2025 15:02:28 -0700 Subject: [PATCH] Feat: Add Gemini moderation for new comments --- functions/api/comments.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/functions/api/comments.js b/functions/api/comments.js index 6cde2b6..d7a3838 100644 --- a/functions/api/comments.js +++ b/functions/api/comments.js @@ -32,6 +32,10 @@ export async function onRequestPost({request,env}){ const{post_id,parent_id,content}=body; if(!post_id||!content)return json({error:'Missing fields'},{status:400},request); + const mod=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent?key=${env.GOOGLE_KEY}`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({contents:[{parts:[{text:`Is this appropriate for a public forum? Respond ONLY "yes" or "no".\n\n${content}`}]}]})}); + if(!mod.ok){const err=await mod.text();return json({error:{message:`Moderation failed: ${err}`}},{status:500},request)} + if((await mod.json()).candidates?.[0]?.content.parts[0].text.trim().toLowerCase()!=='yes')return json({error:{message:'Comment rejected by Gemini 2.5 Flash Lite.'}},{status:400},request); + const{meta}=await env.D1_SPCHCAP.prepare('INSERT INTO comments(post_id,user_id,parent_id,content)VALUES(?,?,?,?)').bind(post_id,user.id,parent_id||null,content).run(); await env.D1_SPCHCAP.prepare('UPDATE posts SET comment_count=comment_count+1 WHERE id=?').bind(post_id).run(); if(parent_id)await env.D1_SPCHCAP.prepare('UPDATE comments SET reply_count=reply_count+1 WHERE id=?').bind(parent_id).run();