chat.controller.js 1.18 KB
Newer Older
Soo Hyun Kim's avatar
Soo Hyun Kim committed
1
2
3
// import { useState } from 'react'
import Chat from "../models/Chat.js"
import { customAlphabet } from 'nanoid'
Soo Hyun Kim's avatar
Soo Hyun Kim committed
4
5
import isLength from 'validator/lib/isLength.js'

Soo Hyun Kim's avatar
Soo Hyun Kim committed
6
7
const nanoid = customAlphabet('1234567890abcdef', 10)

Soo Hyun Kim's avatar
Soo Hyun Kim committed
8
const makeChat = async (req, res) => {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
9
10
11
12
13
14
15
16
17
    const { name, interest, isOpen } = req.body;

    const roomId = nanoid()
    const chat = await Chat.findOne({ roomId })
    while (chat) {
        roomId = nanoid()
        chat = await Chat.findOne({ roomId })
    }

Soo Hyun Kim's avatar
Soo Hyun Kim committed
18
    try {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
19
20
21
22
        if (!isLength(name, { min: 3, max: 20 })) {
            return res.status(422).send('채팅방의 이름은 3-20자여야 합니다.')
        } else if (interest=='Choose...' || interest==''){
            return res.status(422).send('분야를 반드시 선택하여야 합니다.')
Soo Hyun Kim's avatar
Soo Hyun Kim committed
23
        }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
24
25
        const newChat = await new Chat({
            roomId,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
26
27
28
29
30
31
32
33
            name,
            interest,
            isOpen
        }).save()
        console.log(newChat)
        res.json(newChat)
    } catch (error) {
        console.log(error)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
34
        res.status(500).send('방생성 에러')
Soo Hyun Kim's avatar
Soo Hyun Kim committed
35
36
37
38
39
40
41
42
    }
}

const hello = (req, res) => {
    res.send('Hello from users controller')
}

export default { makeChat, hello }