room.controller.js 1.14 KB
Newer Older
Soo Hyun Kim's avatar
Soo Hyun Kim committed
1
import Room from "../models/Room.js"
Soo Hyun Kim's avatar
Soo Hyun Kim committed
2
import { customAlphabet } from 'nanoid'
Soo Hyun Kim's avatar
Soo Hyun Kim committed
3
4
import isLength from 'validator/lib/isLength.js'

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

Soo Hyun Kim's avatar
Soo Hyun Kim committed
7
8
9
10
const makeRoom = async (req, res) => {
    console.log(req.body)
    const { roomName, interest, isOpen } = req.body;
    console.log(roomName, interest, isOpen)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
11
12

    const roomId = nanoid()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
13
14
    const room = await Room.findOne({ roomId })
    while (room) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
15
        roomId = nanoid()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
16
        room = await Room.findOne({ roomId })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
17
18
    }

Soo Hyun Kim's avatar
Soo Hyun Kim committed
19
    try {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
20
        if (!isLength(roomName, { min: 3, max: 20 })) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
21
22
23
            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
24
        }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
25
        const newRoom = await new Room({
Soo Hyun Kim's avatar
Soo Hyun Kim committed
26
            roomId,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
27
            roomName,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
28
29
30
            interest,
            isOpen
        }).save()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
31
32
        console.log(newRoom)
        res.json(newRoom)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
33
34
    } catch (error) {
        console.log(error)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
35
        res.status(500).send('방생성 에러')
Soo Hyun Kim's avatar
Soo Hyun Kim committed
36
37
38
    }
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
39
export default { makeRoom }