-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (69 loc) · 2.41 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const express = require("express");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
var path = require("path");
//const dotenv = require("dotenv").config();
const bodyParser = require("body-parser");
app.use(bodyParser.json());
const name = require("./username");
//connecting the mongo database
const connect = require("./dbConnect");
//const connect = dbConnect(process.env.DBURL);
//new schema instance
const Chat = require("./model/chatschema");
//this is for auto https upgrades for production
const checkHttps = require("./route/httpsUpgrade")
//app.all('*', checkHttps)
// Specify a directory to serve static files
app.use(express.static("public"));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/public"));
});
var usersArr = [];
io.sockets.on("connection", function (socket) {
socket.on("username", function (username) {
//validating username
socket.username = name.validUser(username);
usersArr.push(socket.username);
io.emit("is_online", " <i class='mx-auto'>" + socket.username + " has joined the chat..</i>");
io.emit("users", usersArr);
});
socket.on("disconnect", function (username) {
usersArr.splice(usersArr.indexOf(socket.username), 1);
io.emit("is_online", " <i class='mx-auto'>" + socket.username + " has left the chat..</i>");
io.emit("users", usersArr);
});
//sends info about typing
socket.on("typing", function (data) {
socket.broadcast.emit("typing", data);
});
//sends messages and saves them
socket.on("chat_message", function (message) {
io.emit("chat_message", "" + socket.username + ": " + message);
connect.then((db) => {
let chatMessage = new Chat({
message: message,
username: socket.username,
});
chatMessage.save();
});
});
//sends the previous messages to client
app.get("/chat", (req, res) => {
res.setHeader("Content-Type", "application/json");
res.statusCode = 200;
connect.then((db) => {
Chat.find({}).then((chat) => {
res.json(chat);
});
});
});
app.get("/set/user", function (req, res) {
res.status(200).sendFile(path.join(__dirname, "public", "user.html"));
});
});
const port = 3000 || process.env.PORT;
const server = http.listen(port, function () {
console.log(`listening on *:${port}`);
});