Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Super Chat Project #27

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules
74 changes: 74 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const express = require("express");
const app = express();
const expressHandlebars = require("express-handlebars");
const bodyParser = require("body-parser");
const redisClient = require("redis").createClient();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const cookieParser = require("cookie-parser");

const hbs = expressHandlebars.create({ defaultLayout: "main" });
let chatRooms = ["Cats", "Dogs", "Programmers"];

app.engine("handlebars", hbs.engine);
app.set("view engine", "handlebars");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(`${__dirname}/public`));
app.use(cookieParser());
app.use(
"/socket.io",
express.static(__dirname + "node_modules/socket.io-client/dist/")
);

app.get("/", (req, res) => {
if (req.cookies.nameInput) {
res.render("index", { chatRooms: chatRooms });
} else {
res.render("newUser");
}
});

app.get("/:room", (req, res) => {
res.render("chatroom", {
chatRooms: chatRooms,
currentRoom: req.params.room
});
});

app.post("/postform", (req, res) => {
res.cookie("nameInput", req.body.newName);
res.redirect("/");
});

io.on("connection", client => {
client.on("submit", data => {
let setCommentPromise = data => {
return new Promise((resolve, reject) => {
redisClient.hmset(
"message",
"user",
"Anon",
"userMessage",
data,
(err, result) => (err ? reject(err) : resolve(result))
);
});
};

setCommentPromise(data)
.then(result => {
return new Promise((resolve, reject) => {
redisClient.hgetall(
"message",
(err, object) => (err ? reject(err) : resolve(object))
);
});
})
.then(result => {
io.emit("messages", result);
})
.catch(err => io.emit("error", err));
});
});

server.listen(3000);
Loading