Commit fe9a34d8 authored by 우지원's avatar 우지원
Browse files

오픈채팅방

parent 2689c003
......@@ -19,7 +19,7 @@ function Menu() {
{/* <Nav.Link href="/home">Home</Nav.Link> */}
<Nav.Link href="/profile">Profile</Nav.Link>
</Nav>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light">Logout</Button>
</>
: <Nav className="ml-auto">
<Nav.Link href='/login'>로그인</Nav.Link>
......
......@@ -3,7 +3,7 @@ import { ListGroup } from 'react-bootstrap';
import axios from 'axios'
function OpenList(props) {
const [openlist, setOpenlist] = useState([]);
const [openlist, setOpenlist] = useState([])
useEffect(() => {
getOpenList();
......@@ -15,11 +15,11 @@ function OpenList(props) {
setOpenlist(res.data)
}
function enterChatRoomCH(e) {
const roomName = e.target.name
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
async function enterChatRoomCH(e) {
const roomId = e.target.name
console.log(roomId)
props.openListroom(roomId) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomId)
// props.clearChat()
}
......@@ -27,7 +27,7 @@ function OpenList(props) {
<div>
{openlist.map((item, index) =>
<ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomName}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
{item.roomName}
</ListGroup.Item>
</ListGroup>
......
......@@ -9,13 +9,23 @@ import { io } from "socket.io-client"; //모듈 가져오기
import Chat from "../Components/Chat";
import RoomMake from "../Components/RoomMake"
import EnterRoom from "../Components/EnterRoom"
import axios from 'axios';
const socket = io();
const INIT_ROOM = {
roomName: '',
interest: '',
roomId: '',
member: '',
}
function Home() {
const [showModal, setShowModal] = useState(false);
const [showEnter, setEnter] = useState(false);
const [chat, setChat] = useState(false);
const [open, setOpen] = useState(false);
const [room, setRoom] = useState(INIT_ROOM)
//소켓
const [singleChat, setSingleChat] = useState('')
......@@ -23,24 +33,43 @@ function Home() {
const [roomName, setRoomName] = useState('')
const [roomCode, setRoomCode] = useState('')
//방참가
const [roomId, setRoomId] = useState('')
const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true);
const handleCloseEnter = () => setEnter(false);
const handleShowEnter = () => setEnter(true);
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
const handleChatc = () => setOpen(true);
//SOCKET 관련 시작
//내채팅방에서 채팅시작
function enterChatroom(rName) { //방 입장하기
socket.emit('joinRoom', rName)
console.log(`joinRoom : ${rName} 입장`)
}
//오픈채팅방에서 참가하기
async function openListroom(roomId) {
console.log(roomId)
const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } })
console.log(roomInf)
console.log(roomInf.data)
console.log(roomInf.data.[0])
setRoom(roomInf.data.[0])
}
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) {
alert('참가되었습니다.')
} else {
alert('이미 참가된 방입니다.')
}
}
const sendMsg = (e) => {
e.preventDefault()
}
......@@ -69,23 +98,35 @@ function Home() {
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatroom={enterChatroom} setRoomName={setRoomName} />
</Tab>
<Tab eventKey="open" title="공개방" >
<OpenList enterChatroom={enterChatroom} setRoomName={setRoomName} />
<Tab eventKey="open" title="공개방" onClick={handleChatc}>
<OpenList openListroom={openListroom} setRoomName={setRoomName} />
</Tab>
</Tabs>
</Col>
<Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomName={roomName} /> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>
생성
</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>
참가
</Button>
</div>
{chat ?
<Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomName={roomName} />
: <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
</div>}
{open ?
<div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
<div className="d-flex justify-content-center">
<div className="mt-5 p-5 shadow w-75">
<h2 className="d-flex justify-content-center mb-3">현재 {room.roomName} 입니다.</h2>
<h5> 관심분야 : {room.interest}</h5>
<h5> 참여인원 : {room.member.length}</h5>
<h5> 방코드(방코드를 통해서도 참여할 있습니다.) : {room.roomId}</h5>
<Button className="d-flex flex-end mt-4" variant="primary" type="submit" onClick={attendListRoom}> 참가 </Button>
</div>
</div>
</div> :
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
</div>}
</Col>
</Row>
<RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
......
......@@ -7,8 +7,8 @@ const nanoid = customAlphabet('1234567890abcdef', 10)
const makeRoom = async (req, res) => {
console.log(req.body)
const { roomName, interest, isOpen, member } = req.body;
console.log('콘솔확인',roomName, interest, isOpen, member)
console.log('콘솔확인', roomName, interest, isOpen, member)
//console.log('member저장', member)
const roomId = nanoid()
const room = await Room.findOne({ roomId })
while (room) {
......@@ -40,7 +40,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] })
let list = await Room.find({ member: req.query._id })
console.log('c_list가져오기', list)
return res.json(list)
} catch (error) {
......@@ -48,6 +48,7 @@ const getClosedList = async (req, res) => {
}
}
const getOpenList = async (req, res) => {
try {
let list = await Room.find({ isOpen: true })
......@@ -58,4 +59,57 @@ const getOpenList = async (req, res) => {
}
}
export default { makeRoom, getClosedList, getOpenList }
// const getMemberId = async (req, res) => {
// try {
// console.log('roomId 확인', req.query.roomId)
// let room = await Room.findOne({ roomId: req.query.roomId })
// console.log('room', room)
// const memId = room.member
// console.log('memberId', memId)
// return res.json(memId)
// } catch (error) {
// res.status(500).send('참여자 아이디 불러오는것을 실패하였습니다!')
// }
// }
const changemember = async (req, res) => {
// const memberId = req.memberId
const { userId, roomId } = req.body
console.log('userId:',userId)
let room = await Room.findOne({ roomId: roomId }).select('member')
console.log('room.member:',room.member)
const isPresent = room.member.indexOf(userId)
console.log('isPresent',isPresent)
try {
if (isPresent<0) {
// const member = room.member.toString()
// console.log('member:', member)
const memberId = room.member.push(userId)
console.log('memberId:',memberId)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
return res.json(true)
}
else {
return res.json(false)
}
res.end()
} catch (error) {
console.log(error)
res.status(500).send('멤버 업데이트 실패')
}
}
const roomInf = async (req, res) => {
try {
console.log(req.query.roomId)
// let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec()
let roomInf = await Room.find({ roomId: req.query.roomId })
console.log('room_member로 정보 가져오기:', roomInf)
return res.json(roomInf)
} catch (error) {
alert('올바르지 못한 접근입니다.')
}
}
export default { makeRoom, getClosedList, getOpenList, changemember, roomInf }
......@@ -13,7 +13,7 @@ const profileUpload = upload.fields([
const signup = async (req, res) => {
const { username, nickname, email, password } = req.body
try {
if (!isLength(username, { min: 3, max: 10 })) {
return res.status(422).send('이름은 3-10자 사이입니다')
......
......@@ -16,7 +16,7 @@ const RoomSchema = new mongoose.Schema({
interest: {
type: String,
required: true,
select: false
// select: false
},
isOpen: {
type: Boolean,
......
......@@ -6,9 +6,17 @@ const router = express.Router()
router.route('/room/makeRoom')
.post(roomCtrl.makeRoom)
router.route('/room/changeMem')
.put(roomCtrl.changemember)
.get(roomCtrl.roomInf)
router.route('/room/closedlist')
.get(roomCtrl.getClosedList)
router.route('/room/openlist')
.get(roomCtrl.getOpenList)
// router.route('/room/memberId')
// .get(roomCtrl.getMemberId)
export default router
\ No newline at end of file
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