dh_demo

DreamHanks demo project
git clone git://git.lair.cx/dh_demo
Log | Files | Refs | README

index.ts (2174B)


      1 import { ERR_INTERNAL, ERR_METHOD_NOT_ALLOWED, ERR_UNAUTHORIZED } from '@/lib/apierror'
      2 import { ERR_CODE_DUPLICATED_SLUG, ERR_CODE_INVALID_SLUG, ERR_CODE_INVALID_TITLE } from '@/lib/error_codes'
      3 import { createWiki } from '@/lib/models/wiki_info'
      4 import { authenticationFromCookies } from '@/lib/security/token'
      5 import { NextApiRequest, NextApiResponse } from 'next'
      6 
      7 const regexSlug = /^[a-z0-9-]+$/
      8 
      9 const SLUG_MAX_LENGTH = 48
     10 const TITLE_MAX_LENGTH = 255
     11 
     12 export interface CreateWikiRequest {
     13   slug: string
     14   title: string
     15   description?: string
     16 }
     17 
     18 export default async function handler (req: NextApiRequest, res: NextApiResponse) {
     19   if (req.method !== 'POST') {
     20     res.status(405).json(ERR_METHOD_NOT_ALLOWED)
     21     return
     22   }
     23 
     24   // 토큰 검증
     25   const tokenPayload = await authenticationFromCookies(req.cookies)
     26   const userId = tokenPayload?.uid
     27   if (userId == null) {
     28     res.status(401).json(ERR_UNAUTHORIZED)
     29     return
     30   }
     31 
     32   const { slug, title, description } = req.body as CreateWikiRequest
     33 
     34   // 파라메터 검증
     35   if (slug == null || slug === '') {
     36     res.status(400).json({ code: ERR_CODE_INVALID_SLUG, message: 'slug is required' })
     37     return
     38   }
     39   if (slug.length > SLUG_MAX_LENGTH) {
     40     res.status(400).json({ code: ERR_CODE_INVALID_SLUG, message: 'slug is too long' })
     41     return
     42   }
     43   if (!regexSlug.test(slug)) {
     44     res.status(400).json({ code: ERR_CODE_INVALID_SLUG, message: 'slug is invalid' })
     45     return
     46   }
     47 
     48   if (title == null || title === '') {
     49     res.status(400).json({ code: ERR_CODE_INVALID_TITLE, message: 'title is required' })
     50     return
     51   }
     52   if (title.length > TITLE_MAX_LENGTH) {
     53     res.status(400).json({ code: ERR_CODE_INVALID_TITLE, message: 'title is too long' })
     54     return
     55   }
     56 
     57   // 새 위키를 생성함
     58   try {
     59     await createWiki([userId, slug, title, description ?? null])
     60   } catch (e: any) {
     61     if (e.code === 'ER_DUP_ENTRY') {
     62       res.status(400).json({ code: ERR_CODE_DUPLICATED_SLUG, message: 'slug is already used' })
     63       return
     64     }
     65 
     66     console.error('createWiki: database error:', e)
     67     res.status(500).json(ERR_INTERNAL)
     68     return
     69   }
     70 
     71   return res.status(201).json({ status: 'created' })
     72 }