import { DeleteResult, EntityManager, InsertResult, UpdateResult } from "typeorm"; import { dataSource } from "../../../data-source"; import InternalException from "../../../exceptions/internalException"; import NewsletterRecipientsService from "../../../service/club/newsletter/newsletterRecipientsService"; import { SynchronizeNewsletterRecipientsCommand } from "./newsletterRecipientsCommand"; import { newsletterRecipients } from "../../../entity/club/newsletter/newsletterRecipients"; import DatabaseActionException from "../../../exceptions/databaseActionException"; export default abstract class NewsletterRecipientsCommandHandler { /** * @description sync newsletterRecipients * @param {SynchronizeNewsletterRecipientsCommand} syncNewsletterRecipients * @returns {Promise} */ static async sync(syncNewsletterRecipients: SynchronizeNewsletterRecipientsCommand): Promise { let currentRecipients = (await NewsletterRecipientsService.getAll(syncNewsletterRecipients.newsletterId)).map( (r) => r.memberId ); return await dataSource.manager .transaction(async (manager) => { let newRecipients = syncNewsletterRecipients.recipients.filter( (r) => !currentRecipients.map((np) => np).includes(r) ); let removeRecipients = currentRecipients.filter( (r) => !syncNewsletterRecipients.recipients.map((np) => np).includes(r) ); if (newRecipients.length != 0) { await this.syncPresenceAdd(manager, syncNewsletterRecipients.newsletterId, newRecipients); } if (removeRecipients.length != 0) { await this.syncPresenceRemove(manager, syncNewsletterRecipients.newsletterId, removeRecipients); } }) .then(() => {}) .catch((err) => { throw new DatabaseActionException("SYNC", "newsletterRecipients", err); }); } private static async syncPresenceAdd( manager: EntityManager, newsletterId: number, recipients: Array ): Promise { return await manager .createQueryBuilder() .insert() .into(newsletterRecipients) .values( recipients.map((r) => ({ memberId: r, newsletterId: newsletterId, })) ) .execute(); } private static async syncPresenceRemove( manager: EntityManager, newsletterId: number, recipients: Array ): Promise { return await manager .createQueryBuilder() .delete() .from(newsletterRecipients) .where("memberId IN (:...ids)", { ids: recipients }) .andWhere("newsletterId = :newsletterId", { newsletterId }) .execute(); } }