comments.ts (1460B)
1 import { ERR_BAD_ID, ERR_INTERNAL, ERR_METHOD_NOT_ALLOWED, ERR_UNAUTHORIZED } from '@/lib/apierror' 2 import { ERR_CODE_EMPTY_CONTENT } from '@/lib/error_codes' 3 import { createThreadComment } from '@/lib/models/thread' 4 import { authenticationFromCookies } from '@/lib/security/token' 5 import { parseIdFromQuery } from '@/lib/utils/id' 6 import { NextApiRequest, NextApiResponse } from 'next' 7 8 export default async function handler (req: NextApiRequest, res: NextApiResponse) { 9 switch (req.method) { 10 case 'POST': 11 await handlePost(req, res) 12 break 13 default: 14 res.status(405).json(ERR_METHOD_NOT_ALLOWED) 15 break 16 } 17 } 18 19 async function handlePost (req: NextApiRequest, res: NextApiResponse) { 20 const id = parseIdFromQuery(req.query) 21 if (id == null) { 22 res.status(400).json(ERR_BAD_ID) 23 return 24 } 25 26 const { content } = req.body 27 if (typeof content !== 'string' || content.length === 0) { 28 res.status(400).json({ 29 code: ERR_CODE_EMPTY_CONTENT, 30 message: 'Empty content is not allowed', 31 }) 32 return 33 } 34 35 const tokenPayload = await authenticationFromCookies(req.cookies) 36 if (tokenPayload?.uid == null) { 37 res.status(401).json(ERR_UNAUTHORIZED) 38 return 39 } 40 41 try { 42 await createThreadComment([id, tokenPayload.uid, content]) 43 } catch (e) { 44 console.error('createThreadComment: database error:', e) 45 res.status(500).json(ERR_INTERNAL) 46 return 47 } 48 49 res.status(200).json({ status: 'ok' }) 50 }