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

0125 방 탈퇴 기능

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