improvement: better names on wbot methods

This commit is contained in:
canove
2020-09-05 15:43:52 -03:00
parent b8ff993e6f
commit 40e2e5e8a6
8 changed files with 160 additions and 92 deletions

View File

@@ -1,6 +1,6 @@
const Contact = require("../models/Contact");
const { getIO } = require("../libs/socket");
const { getWbot, init } = require("../libs/wbot");
const { getWbot, initWbot } = require("../libs/wbot");
exports.store = async (req, res, next) => {
const io = getIO();

View File

@@ -1,6 +1,8 @@
const Whatsapp = require("../models/Whatsapp");
const { getIO } = require("../libs/socket");
const { getWbot } = require("../libs/wbot");
const { getWbot, initWbot, removeWbot } = require("../libs/wbot");
const wbotMessageListener = require("../services/wbotMessageListener");
const wbotMonitor = require("../services/wbotMonitor");
exports.index = async (req, res) => {
const dbSession = await Whatsapp.findAll();
@@ -8,6 +10,29 @@ exports.index = async (req, res) => {
return res.status(200).json(dbSession);
};
exports.store = async (req, res) => {
const io = getIO();
const dbSession = await Whatsapp.create(req.body);
if (!dbSession) {
return res.status(400).json({ error: "Cannot create whatsapp session." });
}
initWbot(dbSession)
.then(() => {
wbotMessageListener(dbSession);
wbotMonitor(dbSession);
})
.catch(err => console.log(err));
io.emit("session", {
action: "update",
session: dbSession,
});
return res.status(200).json({ message: "Session created sucessfully." });
};
exports.show = async (req, res) => {
const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId);
@@ -20,6 +45,7 @@ exports.show = async (req, res) => {
};
exports.update = async (req, res) => {
const io = getIO();
const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId);
@@ -29,15 +55,37 @@ exports.update = async (req, res) => {
}
const wbot = getWbot(dbSession.id);
const io = getIO();
wbot.logout();
await dbSession.update(req.body);
wbot.logout();
io.emit("session", {
action: "update",
session: dbSession,
});
return res.status(200).json({ message: "session disconnected" });
return res.status(200).json({ message: "Session updated" });
};
exports.delete = async (req, res) => {
const io = getIO();
const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId);
if (!dbSession) {
return res.status(404).json({ message: "Session not found" });
}
const wbot = getWbot(dbSession.id);
await dbSession.destroy();
removeWbot(dbSession.id);
io.emit("session", {
action: "delete",
sessionId: dbSession.id,
});
return res.status(200).json({ message: "Session deleted." });
};