Skip to content

Commit

Permalink
chore(socket): Broadcast message sent
Browse files Browse the repository at this point in the history
- Add socket.broadcast.emit for sending message
[Delivers #167745847]
  • Loading branch information
ericnyirimana committed Aug 7, 2019
1 parent 8df49bc commit e84c068
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 106 deletions.
2 changes: 1 addition & 1 deletion helpers/messageHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class messageHelper {
include: [
{
model: User,
attributes: ['username']
attributes: ['username', 'image']
}
],
attributes: ['message', 'createdAt']
Expand Down
26 changes: 20 additions & 6 deletions helpers/utils/socketIo.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,37 @@ const { Message, User } = models;
const SocketIO = (app) => {
http.createServer(app);
const port = process.env.PORT || 3000;
const io = socketIo.listen(app.listen(port, () => {
console.log(`Listening on port ${port}`);
}));
const io = socketIo.listen(
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
);
io.use((socket, next) => {
next(null, next);
});
io.on('connection', (socket) => {
socket.on('new_message', async (data) => {
const userId = await userHelper.findUserByToken(data.token);
const user = await User.findOne({ where: { id: userId } });
const { username } = user.dataValues;
const { username, image } = user.dataValues;
const saveMessage = await Message.create({
senderId: userId,
message: data.message
});
if (!saveMessage) socket.emit('message_failed', { error: 'Last message was not sent' });
socket.emit('message_created', { message: data.message, username });
if (!saveMessage) {
socket.emit('message_failed', { error: 'Last message was not sent' });
} else {
socket.broadcast.emit('message_created', {
message: data.message,
User: { username, image },
createdAt: saveMessage.dataValues.createdAt
});
socket.emit('message_created', {
message: data.message,
User: { username, image },
createdAt: saveMessage.dataValues.createdAt
});
}
});
socket.on('disconnect', () => {});
});
Expand Down
199 changes: 100 additions & 99 deletions html/chat.html
Original file line number Diff line number Diff line change
@@ -1,115 +1,116 @@
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

<head>
<title>Socket.IO chat</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Helvetica, Arial;
}

body {
font: 13px Helvetica, Arial;
}
form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}

form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: 0.5%;
}

form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: 0.5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}

form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
}

#messages {
list-style-type: none;
margin: 0;
padding: 0;
}
#messages li {
padding: 5px 10px;
}

#messages li {
padding: 5px 10px;
}
#messages li:nth-child(odd) {
background: #eee;
}

#messages li:nth-child(odd) {
background: #eee;
}
.display {
background-color: teal;
margin-bottom: 5%;
}
</style>
</head>

.display {
background-color: teal;
margin-bottom: 5%;
}
</style>
</head>

<body>
<div class="display">
<ul id="messages"></ul>
</div>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
let socket = io();
function getMessages() {
const route = 'http://localhost:3000/api/v1/messages';
const request = new Request(route, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: localStorage.Authorization
}
});
fetch(request)
.then(res => {
return res.json();
})
.then(resJson => {
for (const msg of resJson.messages) {
// console.log(msg);
$('#messages').append($('<li>').text(msg.message));
$('#messages').append(
$('<li>').text(new Date(msg.createdAt).toDateString())
);
$('#messages').append($('<li>').text(msg.User.username));
<body>
<div class="display">
<ul id="messages"></ul>
</div>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
let socket = io();
function getMessages() {
const route = 'http://localhost:3000/api/v1/messages';
const request = new Request(route, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: localStorage.Authorization
}
});
}
fetch(request)
.then(res => {
return res.json();
})
.then(resJson => {
for (const msg of resJson.messages) {
// console.log(msg);
$('#messages').append($('<li>').text(msg.message));
$('#messages').append(
$('<li>').text(new Date(msg.createdAt).toDateString())
);
$('#messages').append($('<li>').text(msg.User.username));
}
});
}

$(() => {
getMessages();
socket.on('message_created', msg => {
$('#messages').append($('<li>').text(msg.message));
$('#messages').append($('<li>').text(msg.username));
window.scrollTo(0, document.body.scrollHeight);
});
$(() => {
getMessages();
socket.on('message_created', msg => {
$('#messages').append($('<li>').text(msg.message));
$('#messages').append($('<li>').text(msg.username));
window.scrollTo(0, document.body.scrollHeight);
});

$('form').submit(e => {
socket.emit('new_message', { token: localStorage.Authorization, message: $('#m').val() })
$('#m').val() == '';
e.preventDefault();
$('form').submit(e => {
socket.emit('new_message', {
token: localStorage.Authorization,
message: $('#m').val()
});
$('#m').val() == '';
e.preventDefault();
});
});
});
</script>
</body>

</html>
</script>
</body>
</html>

0 comments on commit e84c068

Please sign in to comment.