Commit 8aeb7d25 authored by Soo Hyun Kim's avatar Soo Hyun Kim
Browse files

0125 방 탈퇴 기능

parent a09f29f3
......@@ -9,7 +9,6 @@ function Chat(props) {
const [sender, setSender] = useState([])
const [roomName, setRoomName] = useState('')
const [inner, setInner] = useState([''])
const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지
......@@ -19,8 +18,10 @@ function Chat(props) {
const [user, setUser] = useState('')
const [error, setError] = useState('');
const [exit, setExit] = useState(false);
const userId = isAuthenticated()
async function getProfile(userId) {
try {
const response = await axios.get(`/users/${userId}`)
......@@ -30,16 +31,6 @@ function Chat(props) {
}
}
async function getRoomName(roomCode) {
try {
let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
console.log(res.data)
setRoomName(res.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleChange(e) {
e.preventDefault()
setInner(e.target.value)
......@@ -59,10 +50,19 @@ function Chat(props) {
}
function handleClick() {
setChat([])
props.closeChatRoom(props.roomCode)
props.setRecievedMsg('')
console.log(chat)
props.handleChatc()
}
async function exitAndCloseRoom(){
props.exitRoom(props.roomCode)
setExit(false)
props.handleChatc()
}
useEffect(() => {
getProfile(userId)
}, [userId])
......@@ -71,6 +71,8 @@ function Chat(props) {
setImg([...img, props.singleImg])
setSender([...sender, props.singleUser])
setChat([...chat, props.singleChat])
console.log('chat', chat)
console.log('sender', sender)
}, [props.singleChat])
useEffect(() => {
......@@ -79,23 +81,28 @@ function Chat(props) {
setChat([...chat, props.recievedMsg])
}, [props.recievedMsg])
useEffect(() => {
getRoomName(props.roomCode)
}, [props.roomCode])
const time = new Date().toLocaleTimeString()
return (
<>
<Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
<Row className="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}>
<Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
<Col md="auto">
<Button variant="light" onClick={handleClick} >{`<`}</Button>
</Col>
<Col>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
<Row > {props.roomCode} </Row>
</Col>
<Col md="auto">
<Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
</Col>
</Row>
{exit ?
<Row>
<Col>퇴장하시겠습니까?</Col>
<Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
</Row>
: null}
<p>{props.newUser}님이 입장하셨습니다.</p>
{chat.map((value, index) => {
if (!(value == '')) {
......
......@@ -17,10 +17,14 @@ function ClosedList(props) {
}
function enterChatRoomCH(e) {
if (props.roomCode){
props.closeChatRoom(props.roomCode)
}
const roomCode = e.target.name
const roomName = e.target.value
props.enterChatRoom(roomCode)
props.setRoomCode(roomCode)
props.setRoomName(roomName)
}
return (
......
......@@ -16,6 +16,10 @@ function OpenList(props) {
function enterChatRoomCH(e) {
if (props.roomCode){
props.closeChatRoom(props.roomCode)
}
console.log('e확인', e.target)
const roomCode = e.target.name
// props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
......
......@@ -22,6 +22,7 @@ const INIT_ROOM = {
function Home() {
const userName = sessionStorage.getItem('name')
const userId = sessionStorage.getItem('userId');
const [showModal, setShowModal] = useState(false);
const [showEnter, setShowEnter] = useState(false);
......@@ -35,6 +36,7 @@ function Home() {
const [recievedMsg, setRecievedMsg] = useState('')
const [roomCode, setRoomCode] = useState('')
const [newUser, setNewUser] = useState('')
const [roomName, setRoomName] = useState('')
const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('')
......@@ -42,15 +44,6 @@ function Home() {
const [singleImg, setSingleImg] = useState('')
const [recievedImg, setRecievedImg] = useState('')
//SOCKET 관련 시작
function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`)
}
const [roomName, setRoomName] = useState('')
const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true);
const handleCloseEnter = () => setShowEnter(false);
......@@ -58,10 +51,29 @@ function Home() {
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
//SOCKET 방 enter, close, exit event
function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`)
}
socket.on("sendUser", (data) => {
setNewUser(data)
})
function closeChatRoom(rCode) {
socket.emit('closeRoom', rCode)
console.log(`${rCode}방 보기 중단`)
}
async function exitRoom(roomId) {
await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
console.log(`${roomId}${userId} 탈퇴`)
setRoomCode("")
}
//오픈채팅방에서 참가하기
async function openListroom(roomId) {
console.log(roomId)
......@@ -75,7 +87,6 @@ function Home() {
}
async function attendListRoom() {
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
const roomId = room.roomId
const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
if (tf.data) {
......@@ -94,7 +105,7 @@ function Home() {
useEffect(() => {
if (!(singleChat == '')) {
if (!(singleChat == "")){
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: {
......@@ -103,7 +114,7 @@ function Home() {
img: singleImg
}
})
setSingleChat([''])
setSingleChat("")
}
}, [singleChat])
......@@ -113,6 +124,7 @@ function Home() {
setRecievedImg(sendInfo.img)
setRecievedUser(sendInfo.sender)
setRecievedMsg(sendInfo.msg)
console.log(sendInfo.msg)
})
}, [])
......@@ -123,10 +135,10 @@ function Home() {
<Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} />
<ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom}/>
</Tab>
<Tab eventKey="open" title="공개방" onClick={handleChatc}>
<OpenList enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} />
<OpenList enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom}/>
</Tab>
</Tabs>
</Col>
......@@ -140,7 +152,7 @@ function Home() {
</div>
}
{chat ?
<Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} roomCode={roomCode} roomName={roomName} />
<Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} setSingleChat={setSingleChat} setRecievedMsg={setRecievedMsg} setSingleUser={setSingleUser} setSingleImg={setSingleImg} roomCode={roomCode} roomName={roomName} closeChatRoom={closeChatRoom} exitRoom={exitRoom}/>
: null}
{open ?
<div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
......
......@@ -38,9 +38,7 @@ const makeRoom = async (req, res) => {
const getClosedList = async (req, res) => {
try {
console.log('req확인', req.query._id)
let list = await Room.find({ member: req.query._id })
console.log('c_list가져오기', list)
return res.json(list)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
......@@ -50,7 +48,6 @@ const getClosedList = async (req, res) => {
const getOpenList = async (req, res) => {
try {
let list = await Room.find({ isOpen: true })
console.log('o_list가져오기', list)
return res.json(list)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
......@@ -76,7 +73,7 @@ const changemember = async (req, res) => {
let room = await Room.findOne({ roomId: roomId }).select('member')
const isPresent = room.member.indexOf(userId)
try {
if (isPresent<0) {
if (isPresent < 0) {
const memberId = room.member.push(userId)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log('room.member 업데이트 완료')
......@@ -91,6 +88,22 @@ const changemember = async (req, res) => {
}
}
const deleteUserId = async (req, res) => {
console.log(req.body)
const { userId, roomId } = req.body
let room = await Room.findOne({ roomId: roomId }).select('member')
console.log('deletetest', room)
const memIndex = room.member.indexOf(userId)
try {
room.member.splice(memIndex, 1)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log(`${roomId}${userId}삭제완료`)
return res.json(true)
} catch (error) {
res.status(500).send('멤버 업데이트 실패')
}
}
const roomInf = async (req, res) => {
try {
console.log(req.query.roomId)
......@@ -103,4 +116,4 @@ const roomInf = async (req, res) => {
}
}
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf }
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, deleteUserId, roomInf }
......@@ -21,4 +21,8 @@ router.route('/room/member')
router.route('/room/getRoomName')
.get(roomCtrl.getRoomName)
router.route('/room/deleteMem')
.put(roomCtrl.deleteUserId)
export default router
\ No newline at end of file
......@@ -28,6 +28,12 @@ io.on("connection", (socket) => { // 기본 연결
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
});
socket.on('closeRoom', (data) => {
console.log('close_data확인', data)
let roomInfo = data;
socket.leave(roomInfo); //클라이언트에서 data에 적힌 room정보를 브로드캐스팅 받지 않는다.
});
socket.on('newUser', (data) => {
console.log('newUser', data)
let userInfo = data.userInfo;
......@@ -53,7 +59,6 @@ io.on("connection", (socket) => { // 기본 연결
socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id)
})
});
app.use(bodyParser.json());
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment