방정보창에 유저 매칭해서 사진띄우기
//방 정보창
router.get('/info/:roomId', async (req, res)=> {
try {
const { roomId } = req.params
const checkRoom = await Room.findOne({ roomId: roomId })
if (!checkRoom) { return res.status(400).json({ result: false, msg: "방을 찾을 수 없습니다." }) }
const { attendName } = await Room.findOne({ roomId: roomId })
//참여인원 프로필사진 각각 매칭해서 출력하기
console.log(attendName)
//방에 참여중인 인원만 파악해서 출력
let attendInfo = []
for (let i in attendName ) {
if (await User.find({ nickname: attendName[i] })) {
attendInfo.push(await User.find({ nickname: attendName[i] }))
}
}
console.log(attendInfo)
//위 조건의 결과를 이중for문으로 뽑아내고,
//동적인 key값을 적용시켜 출력하려했으나 output [{ aa: bb}]
//프론트요청으로 각각 키값을 넣어줬다. output [{ key: aa, key: bb}]
let output = []
let keyname = ''
let nick = 'nickname'
let image = 'imageUrl'
for (let i in attendInfo) {
for (let j in attendInfo[i]) {
const aa = attendInfo[i][j].nickname
const bb = attendInfo[i][j].profile_url
let something = {}
something[nick] = aa
something[image] = bb
output.push(something)
}
}
return res.status(200).json({
result: true,
checkRoom,
attend: attendName.length,
output,
})
} catch (error) {
console.log(error)
res.status(400).send({ result: false, errorMessage: error.message})
}
})
방정보 결과창
//방정보 결과창
{
"result": true,
"checkRoom": {
"date": [],
"likeUser": [],
"_id": "62e1463a80f1860b92cc0795",
"hostId": 11,
"attendName": [
"호욱10"
],
"title": "소방방방",
"content": "내용",
"groupNum": 2,
"isLiked": false,
"createAt": "2022-07-27T14:04:35.018Z",
"tagName": [
"소방관"
],
"roomId": 26,
"__v": 0
},
"attend": 2,
"output": [
{
"nickname": "호욱10",
"imageUrl": "https://lastproject01.s3.ap-northeast-2.amazonaws.com/uploadProfile/6821659162010962.jpg"
}
]
}
방 탈퇴
//host가 방탈퇴 시 방삭제
router.post('/outroom/:roomId/:userId', authMiddleware, async (req, res)=> {
try {
const roomId = Number(req.params.roomId)
const userId = Number(req.params.userId)
const { groupNum, title, attendName, hostId } = await Room.findOne({ roomId: roomId })
console.log(attendName)
const { nickname } = await User.findOne({ userId: userId })
const checkName = attendName.includes(nickname)
console.log(checkName)
//호스트인경우 방삭제
if (hostId === userId) {
await Room.findOneAndDelete({ roomId },{ hostId: userId });
await User.findOneAndUpdate({ userId }, {$pull : { hostRoom: roomId }})
//방이 없어지므로 방참여중인 유저들의 갖고있는 방정보 같이 빼준다.
await User.updateMany({}, {$pull : { attendRoom: roomId }})
return res.status(200).json({ result: true, msg: "호스트인 스터디룸을 탈퇴 하였습니다." })
}
if (checkName === false) {
return res.status(400).json({ result: false, msg: "참여중인 룸이 아닙니다." })
}
if (groupNum <=0){ return res.status(400).json({result: false, msg: "참여 인원이 없습니다."})}
await Room.updateOne({ roomId: roomId }, { $inc: { groupNum: -1 } });
await Room.findOneAndUpdate({ roomId },{ $pull: { attendName: nickname }});
await User.findOneAndUpdate({ userId }, { $pull: { attendRoom: roomId } })
return res.status(200).json({
result: true,
msg: `${title} 스터디룸을 탈퇴 하였습니다.`
})
} catch (error) {
console.log(error)
res.status(400).send({ result: false, errorMessage: error.message})
}
})
유저 초대하기
//유저 초대하기
router.put('/invite', authMiddleware, async (req, res) => {
try {
const roomId = Number(req.params.roomId)
const userId = Number(req.params.userId)
const { nickname } = await User.findOne({ userId: userId })
const { attendName } = await Room.findOne({ roomId: roomId })
const checkName = attendName.includes(nickname)
if ( checkName === true ) {
return res.status(400).json({ result: false, msg: `${nickname}님은 이미 참여 중입니다.` })
}
if (attendName.length >=4){
return res.status(400).json({result: false, msg: "정원 초과입니다."})}
await Room.updateOne({ roomId: roomId }, { $inc: { groupNum: 1 } });
await Room.findOneAndUpdate({ roomId }, { $push: { attendName: nickname }});
await User.findOneAndUpdate({ userId }, { $push : { attendRoom: roomId }})
return res.status(200).json({
result: true,
nickname,
msg: `${nickname}님을 초대했어요!`
})
} catch (error) {
console.log(error);
res.status(400).send({ errorMessage: error.message });
}
});
참여중인 스터디 조회
참여중인 방정보를 저장할때 정보데이터값이 아닌 roomId(방번호)만 받게 되었어서
방정보 데이터를 뽑아낸다.
//참여중인 스터디 조회
router.get('/entered-room/:userId', authMiddleware, async (req, res) => {
try {
const userId = Number(req.params.userId)
const { attendRoom } = await User.findOne({ userId }).sort("-createAt")
let flat = []
for (let i in attendRoom) {
if(await Room.find({ roomId: attendRoom[i] })){
flat.push(await Room.find({ roomId: attendRoom[i] }))
}
}
const attendInfo = flat.flat(1)
return res.status(200).json({
result: true,
attendInfo,
quantity: attendRoom.length,
})
} catch (error) {
console.log(error);
res.status(400).send({ errorMessage: error.message });
}
});
비밀방 입장
// 비밀방 입장
router.post('/private-room/:roomId/:userId', authMiddleware, async (req, res) => {
try {
const roomId = Number(req.params.roomId);
const userId = Number(req.params.userId)
const { password } = req.body;
const passCheck = await Room.findOne({ roomId: roomId });
const { groupNum, title, attendName } = await Room.findOne({ roomId: roomId });
const { nickname } = await User.findOne({ userId: userId })
const checkName = attendName.includes(nickname)
//패스워드 체크
if (!password) {
return res.status(400).json({ result: false, msg: "비밀번호를 입력해주세요." })
}
if (passCheck.password !== password) {
return res.status(401).send({ msg: '비밀번호가 틀렸습니다 ' });
}
//이미 참여인원이면 실시간 인원수만 추가
if (checkName === true) {
if (groupNum >= 4) {
return res.status(400).send({
result: false,
msg: '정원이 초과되었습니다.',
});
}
await Room.updateOne({ roomId: roomId }, { $inc: { groupNum: 1 } });
return res.status(200).json({ result: true, msg: `'${title}'에 입장하였습니다.` })
}
//미참여인원은 참여정원확인 후 입장
if (attendName.length >= 4) {
return res.status(400).send({
result: false,
msg: '정원이 초과되었습니다.',
});
}
await Room.updateOne({ roomId: roomId }, { $inc: { groupNum: 1 } });
await Room.updateOne({ roomId: roomId }, { $push: { attendName: nickname } });
const roomInfo = await Room.findOne({ roomId: roomId }) //정보 최신화
await User.updateOne({ userId: userId }, { $push: { attendRoom: roomId } })
찜하기
// 찜하기
router.post('/like/:roomId/:userId', authMiddleware, async (req, res) => {
try {
const roomId = Number(req.params.roomId);
const userId = Number(req.params.userId);
// const nickname = req.nickname;
console.log(userId) //내 아이디
const { likeUser, title } = await Room.findOne({ roomId })
console.log(likeUser) //방안에 유저아이디
let likeStatus = ''
let msg = ''
//해당 방안에 내 아이디 유무확인
if (!likeUser.includes(userId)) {
await Room.updateOne({ roomId }, { $push: { likeUser: userId } })
await User.updateOne({ userId }, { $push: { userLike: roomId } });
const aaa = await Room.findOne({ roomId })
console.log(aaa.likeUser) //추가된 방안에 유저아이디
likeStatus = true
msg = `${title}방을 찜 했어요!`
}
else {
await Room.updateOne({ roomId }, { $pull: { likeUser: userId } })
await User.updateOne({ userId }, { $pull: { userLike: roomId } });
const aaa = await Room.findOne({ roomId })
console.log(aaa.likeUser) //추가된 방안에 유저아이디
likeStatus = false
msg = `${title}방 찜 해제`
}
const [user] = await Room.find({ roomId })
const likedUser = user.likeUser
console.log(likedUser)
return res.status(201).send({
// result: true,
likeUser: likedUser,
likeStatus: likeStatus,
msg: msg,
});
} catch (error) {
console.log(error)
return res.status(400).send({ errorMessage: error.message })
}
});
카테고리(페이지네이션)
//카테고리
127.0.0.1:3000/api/main/tag/공무원?page=1&perPage=6
router.get('/tag/:tagName', async (req, res) => {
try {
const { tagName } = req.params;
const page = Number(req.query.page || 1);
const perPage = Number(req.query.perPage || 6)
const roomLength = await Room.find({ tagName });
const tagLength = roomLength.length;
const roomList = await Room.find({ tagName })
.sort({ $natural: -1 })
.skip(perPage * (page - 1))
.limit(perPage)
res.status(200).json({
result: true,
roomList,
tagLength,
});
} catch (error) {
console.log(error);
res.status(400).send({ errorMessage: error.message });
}
});