diff --git a/api/chat.js b/api/chat.js index e319d4a..03be510 100644 --- a/api/chat.js +++ b/api/chat.js @@ -1,4 +1,7 @@ -module.exports = io => { +const path = require("path"); +const { addMessage } = require(path.join(__dirname + "/redis.js")); + +const io = (io) => { io.on("connection", socket => { let username = null; @@ -19,7 +22,10 @@ module.exports = io => { socket.on("chat", msg => { msg.username = username; msg.timestamp = new Date().getTime(); + addMessage(msg); io.emit("chat", msg); }); }); }; + +module.exports = io; diff --git a/api/chatHistory.js b/api/chatHistory.js new file mode 100644 index 0000000..dc1862c --- /dev/null +++ b/api/chatHistory.js @@ -0,0 +1,33 @@ +const express = require("express"); +const path = require("path"); +const router = express.Router(); + +const { history, clearHistory } = require(path.join(__dirname + "/../api/redis")); + +router.use((req, res, next) => { + next(); +}); + +router.route("/chat/history").get(async (req, res) => { + let { skip, take } = req.query; + skip = !isNaN(skip) ? Number(skip) : undefined; + take = !isNaN(take) ? Number(take) : undefined; + + try { + const messages = await history(skip, take); + res.json(messages) + } catch(error) { + res.status(500).send(error); + } +}); + +router.route("/chat/history").delete(async (req, res) => { + try { + const messages = await clearHistory(); + res.json(messages) + } catch(error) { + res.status(500).send(error); + } +}); + +module.exports = router; diff --git a/server.js b/server.js index 9aa428f..f727fd4 100644 --- a/server.js +++ b/server.js @@ -15,6 +15,7 @@ const virtualApi = require(path.join(__dirname + "/api/virtualLottery")); //This is required for the chat to work const chat = require(path.join(__dirname + "/api/chat"))(io); +const chatHistory = require(path.join(__dirname + "/api/chatHistory")); const bodyParser = require("body-parser"); @@ -89,6 +90,7 @@ app.use("/", loginApi); app.use("/api/", updateApi); app.use("/api/", retrieveApi); app.use("/api/", wineinfoApi); +app.use("/api/", chatHistory); app.use("/api/virtual/", virtualApi(io)); app.use("/subscription", subscriptionApi);