projeto-hit/backend/src/services/WbotServices/ImportContactsService.ts

53 lines
1.4 KiB
TypeScript

import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import { getWbot } from "../../libs/wbot";
import Contact from "../../models/Contact";
import { logger } from "../../utils/logger";
import { createOrUpdateContactCache } from '../../helpers/ContactsCache'
const ImportContactsService = async (): Promise<void> => {
const defaultWhatsapp = await GetDefaultWhatsApp();
const wbot = getWbot(defaultWhatsapp.id);
let phoneContacts;
try {
phoneContacts = await wbot.getContacts();
} catch (err) {
logger.error(`Could not get whatsapp contacts from phone. Err: ${err}`);
}
if (phoneContacts) {
await Promise.all(
phoneContacts.map(async ({ number, name }) => {
if (!number) {
return null;
}
if (!name) {
name = number;
}
const numberExists = await Contact.findOne({
where: { number }
});
if (numberExists) return null;
let contact = await Contact.create({ number, name });
// await contact.reload()
// TEST DEL
await createOrUpdateContactCache(`contact:${contact.id}`, {id:contact.id, name, number, profilePicUrl: contact.profilePicUrl, isGroup: contact.isGroup, extraInfo: '', email:'' })
//
// return Contact.create({ number, name });
return contact
})
);
}
};
export default ImportContactsService;