skailan-contacts
Version:
Servicio de gestión de contactos para Skailan
61 lines • 2.84 kB
JavaScript
import { Contact } from '../../domain/entities/Contact';
import { v4 as uuidv4 } from 'uuid';
export class CreateContact {
contactRepository;
constructor(contactRepository) {
this.contactRepository = contactRepository;
}
async execute(request) {
try {
const { organizationId, externalId, name, email, phone, profilePictureUrl, metadata } = request;
// Validate required fields
if (!organizationId) {
throw new Error('Organization ID is required');
}
if (!externalId) {
throw new Error('External ID is required');
}
// Validate email format if provided
if (email && !this.isValidEmail(email)) {
throw new Error('Invalid email format');
}
// Validate phone format if provided
if (phone && !this.isValidPhone(phone)) {
throw new Error('Invalid phone format');
}
// Check for existing contact by externalId
const existingContactByExternalId = await this.contactRepository.findByExternalId(externalId, organizationId);
if (existingContactByExternalId) {
throw new Error('Contact with this external ID already exists for this organization.');
}
// Check for existing contact by email if provided
if (email) {
const existingContactByEmail = await this.contactRepository.findByEmail(email, organizationId);
if (existingContactByEmail) {
throw new Error('Contact with this email already exists for this organization.');
}
}
// Check for existing contact by phone if provided
if (phone) {
const existingContactByPhone = await this.contactRepository.findByPhone(phone, organizationId);
if (existingContactByPhone) {
throw new Error('Contact with this phone already exists for this organization.');
}
}
const newContact = new Contact(uuidv4(), organizationId, externalId, name || null, email || null, phone || null, profilePictureUrl || null, metadata || null, new Date(), new Date());
return await this.contactRepository.save(newContact);
}
catch (error) {
throw new Error(`Error creating contact: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
isValidPhone(phone) {
const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
return phoneRegex.test(phone.replace(/\s/g, ''));
}
}
//# sourceMappingURL=CreateContact.js.map