Files
whaticket-community/backend/src/controllers/WhatsAppController.ts
2020-10-21 20:08:50 -03:00

110 lines
2.7 KiB
TypeScript

import { Request, Response } from "express";
import { getIO } from "../libs/socket";
import { initWbot, removeWbot } from "../libs/wbot";
import wbotMessageListener from "../services/WbotServices/wbotMessageListener";
import wbotMonitor from "../services/WbotServices/wbotMonitor";
import CreateWhatsAppService from "../services/WhatsappService/CreateWhatsAppService";
import DeleteWhatsAppService from "../services/WhatsappService/DeleteWhatsAppService";
import ListWhatsAppsService from "../services/WhatsappService/ListWhatsAppsService";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppService";
interface WhatsappData {
name: string;
status?: string;
isDefault?: boolean;
}
export const index = async (req: Request, res: Response): Promise<Response> => {
const whatsapps = await ListWhatsAppsService();
return res.status(200).json(whatsapps);
};
export const store = async (req: Request, res: Response): Promise<Response> => {
const { name, status, isDefault }: WhatsappData = req.body;
const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({
name,
status,
isDefault
});
initWbot(whatsapp)
.then(() => {
wbotMessageListener(whatsapp);
wbotMonitor(whatsapp);
})
.catch(err => console.log(err));
const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsapp
});
if (oldDefaultWhatsapp) {
io.emit("whatsapp", {
action: "update",
whatsapp: oldDefaultWhatsapp
});
}
return res.status(200).json(whatsapp);
};
export const show = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId);
return res.status(200).json(whatsapp);
};
export const update = async (
req: Request,
res: Response
): Promise<Response> => {
const { whatsappId } = req.params;
const whatsappData = req.body;
const { whatsapp, oldDefaultWhatsapp } = await UpdateWhatsAppService({
whatsappData,
whatsappId
});
const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsapp
});
if (oldDefaultWhatsapp) {
io.emit("whatsapp", {
action: "update",
whatsapp: oldDefaultWhatsapp
});
}
return res.status(200).json(whatsapp);
};
export const remove = async (
req: Request,
res: Response
): Promise<Response> => {
const { whatsappId } = req.params;
await DeleteWhatsAppService(whatsappId);
removeWbot(+whatsappId);
const io = getIO();
io.emit("whatsapp", {
action: "delete",
whatsappId: +whatsappId
});
return res.status(200).json({ message: "Whatsapp deleted." });
};