room.controller.js 4.78 KB
Newer Older
Soo Hyun Kim's avatar
Soo Hyun Kim committed
1
import Room from "../models/Room.js"
우지원's avatar
우지원 committed
2
import { customAlphabet } from 'nanoid'
Soo Hyun Kim's avatar
Soo Hyun Kim committed
3
import isLength from 'validator/lib/isLength.js'
4
import Chat from "../models/Chat.js"
5
import EntryLog from "../models/EntryLog.js"
Soo Hyun Kim's avatar
Soo Hyun Kim committed
6

우지원's avatar
우지원 committed
7
const nanoid = customAlphabet('1234567890abcdef', 10)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
8

Soo Hyun Kim's avatar
Soo Hyun Kim committed
9
const makeRoom = async (req, res) => {
Choi Ga Young's avatar
Choi Ga Young committed
10
    const { roomName, interest, isOpen, member } = req.body;
우지원's avatar
우지원 committed
11
12
13
14
15
16
    const roomId = nanoid()
    const room = await Room.findOne({ roomId })
    while (room) {
        roomId = nanoid()
        room = await Room.findOne({ roomId })
    }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
17

Soo Hyun Kim's avatar
Soo Hyun Kim committed
18
    try {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
19
        if (!isLength(roomName, { min: 3, max: 20 })) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
20
            return res.status(422).send('채팅방의 이름은 3-20자여야 합니다.')
Choi Ga Young's avatar
Choi Ga Young committed
21
        } else if (interest == 'Choose...' || interest == '') {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
22
            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
        const newRoom = await new Room({
우지원's avatar
e    
우지원 committed
25
            roomId,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
26
            roomName,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
27
            interest,
우지원's avatar
수정    
우지원 committed
28
            isOpen,
우지원's avatar
e    
우지원 committed
29
            member,
Soo Hyun Kim's avatar
Soo Hyun Kim committed
30
        }).save()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
31
        res.json(newRoom)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
32
33
    } 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
    }
}

Choi Ga Young's avatar
Choi Ga Young committed
38
39
const getClosedList = async (req, res) => {
    try {
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
40
        let list = await Room.find({ member: req.query._id })
우지원's avatar
e    
우지원 committed
41
42
43
44
45
46
47
48
49
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

const getOpenList = async (req, res) => {
    try {
        let list = await Room.find({ isOpen: true })
Choi Ga Young's avatar
Choi Ga Young committed
50
51
52
53
54
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}
우지원's avatar
수정    
우지원 committed
55

Soo Hyun Kim's avatar
Soo Hyun Kim committed
56
57
58
59
60
61
62
63
64
65
66
const getRoomName = async (req, res) => {
    const roomId = req.query.roomCode

    try {
        let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
        return res.json(roominfo.roomName)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
67
68
69
70
71
const changemember = async (req, res) => {
    const { userId, roomId } = req.body
    let room = await Room.findOne({ roomId: roomId }).select('member')
    const isPresent = room.member.indexOf(userId)
    try {
Choi Ga Young's avatar
x    
Choi Ga Young committed
72
        if (isPresent < 0) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
73
74
            const memberId = room.member.push(userId)
            await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
우지원's avatar
우지원 committed
75
76
77
78
            return res.json(true)
        }
        else {
            return res.json(false)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
79
80
81
82
83
84
        }
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
85
86
87
88
89
90
91
92
93
94
95
96
97
const deleteUserId = async (req, res) => {
    const { userId, roomId } = req.body
    let room = await Room.findOne({ roomId: roomId }).select('member')
    const memIndex = room.member.indexOf(userId)
    try {
        room.member.splice(memIndex, 1)
        await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
        return res.json(true)
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

우지원's avatar
우지원 committed
98
99
100
101
102
103
104
105
106
const roomInf = async (req, res) => {
    try {
        let roomInf = await Room.find({ roomId: req.query.roomId })
        return res.json(roomInf)
    } catch (error) {
        alert('올바르지 못한 접근입니다.')
    }
}

107

JeongYeonwoo's avatar
JeongYeonwoo committed
108
const unreadMessage = async (req, res) => {
109
110
111
112
113
    const nowTime = new Date().toISOString()
    let leaveInfo = req.query
    try {
        for (const key in Object.keys(leaveInfo)) {
            leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
JeongYeonwoo's avatar
JeongYeonwoo committed
114
        }
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        let countArr = []
        for (const key in Object.keys(leaveInfo)) {
            const room = await Room.findOne({ roomId: leaveInfo[key].roomCode })    //들어온 방 코드로 그 방의 정보 찾아옴
            const entrylog = await EntryLog.findOne({ userId: leaveInfo[key].userId, room: room._id }) //그 방에서 나간시간 가져옴
            if (entrylog) {
                if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                } else {
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                }
            } else {
                countArr.push(0)
            }
JeongYeonwoo's avatar
JeongYeonwoo committed
131
        }
132
133
134
        res.json(countArr)
    } catch (error) {
        res.send(error)
JeongYeonwoo's avatar
JeongYeonwoo committed
135
136
    }
}
137
138


139
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, deleteUserId }