room.controller.js 6.38 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'
Choi Ga Young's avatar
x    
Choi Ga Young committed
4
//import AccessInfo from '../models/AccessInfo.js'
5
import Chat from "../models/Chat.js"
6
import EntryLog from "../models/EntryLog.js"
Soo Hyun Kim's avatar
Soo Hyun Kim committed
7

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

Soo Hyun Kim's avatar
Soo Hyun Kim committed
10
const makeRoom = async (req, res) => {
11
    // console.log(req.body)
Choi Ga Young's avatar
Choi Ga Young committed
12
    const { roomName, interest, isOpen, member } = req.body;
13
    // console.log('콘솔확인', roomName, interest, isOpen, member)
우지원's avatar
우지원 committed
14
15
16
17
18
19
    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
20

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

Choi Ga Young's avatar
Choi Ga Young committed
42
43
const getClosedList = async (req, res) => {
    try {
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
44
        let list = await Room.find({ member: req.query._id })
우지원's avatar
e    
우지원 committed
45
46
47
48
49
50
51
52
53
        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
54
55
56
57
58
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}
우지원's avatar
수정    
우지원 committed
59

Soo Hyun Kim's avatar
Soo Hyun Kim committed
60
61
const getRoomName = async (req, res) => {
    const roomId = req.query.roomCode
62
    // console.log('getRoomName', req.query.roomCode)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
63
64
65

    try {
        let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
66
        // console.log(roominfo.roomName)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
67
68
69
70
71
72
        return res.json(roominfo.roomName)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

Choi Ga Young's avatar
x    
Choi Ga Young committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// const sysMsg = async (req, res) => {
//     try {
//         console.log('sysreq', req.query)
//         let rmif = await Room.find({ roomId: req.query.roomCode })
//         console.log('rmif', rmif)
//         let rmid = await AccessInfo.find({ room: rmif._id })
//         console.log('rmid', rmid)

//         if (rmid.isEnt) {
//             let msg = `${rmif.nickname}이 들어왔습니다`
//         } else {

//         }

//     } catch (error) {
//         res.status(500).send('')
//     }
// }

Soo Hyun Kim's avatar
Soo Hyun Kim committed
92
93
const changemember = async (req, res) => {
    const { userId, roomId } = req.body
94
    // console.log(roomId)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
95
96
97
    let room = await Room.findOne({ roomId: roomId }).select('member')
    const isPresent = room.member.indexOf(userId)
    try {
98
        if (isPresent < 0) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
99
100
            const memberId = room.member.push(userId)
            await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
101
            // console.log('room.member 업데이트 완료')
우지원's avatar
우지원 committed
102
103
104
105
            return res.json(true)
        }
        else {
            return res.json(false)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
106
107
108
109
110
111
        }
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
112
const deleteUserId = async (req, res) => {
113
    // console.log(req.body)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
114
115
    const { userId, roomId } = req.body
    let room = await Room.findOne({ roomId: roomId }).select('member')
116
    // console.log('deletetest', room)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
117
118
119
120
    const memIndex = room.member.indexOf(userId)
    try {
        room.member.splice(memIndex, 1)
        await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
121
        // console.log(`${roomId}방 ${userId}삭제완료`)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
122
        return res.json(true)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
123
124
125
126
127
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

우지원's avatar
우지원 committed
128
129
const roomInf = async (req, res) => {
    try {
130
        // console.log(req.query.roomId)
우지원's avatar
우지원 committed
131
132
        // let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec()
        let roomInf = await Room.find({ roomId: req.query.roomId })
133
        // console.log('room_member로 정보 가져오기:', roomInf)
우지원's avatar
우지원 committed
134
135
136
137
138
139
        return res.json(roomInf)
    } catch (error) {
        alert('올바르지 못한 접근입니다.')
    }
}

140
141

////////////////////////////////////////////////////////////////////////////////////////////
JeongYeonwoo's avatar
JeongYeonwoo committed
142
const unreadMessage = async (req, res) => {
143
144
145
146
147
148
149
    const nowTime = new Date().toISOString()
    let leaveInfo = req.query
    console.log('서버의 언리드 리브인포', leaveInfo)
    try {
        for (const key in Object.keys(leaveInfo)) {
            leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
        }
150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        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) {
                console.log('자이거는 서버다!', leaveInfo[key].now)
                if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                    // countArr.push({ roomCode: room.roomId, unreadcount: count })
                } else {
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                    // countArr.push({ roomCode: room.roomId, unreadcount: count })
                }
            } else {
                countArr.push(0)
            }
JeongYeonwoo's avatar
JeongYeonwoo committed
169
        }
170
171
172
        res.json(countArr)
    } catch (error) {
        res.send(error)
JeongYeonwoo's avatar
JeongYeonwoo committed
173
174
    }
}
175
176


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