import { DeleteResult, EntityManager, InsertResult } from "typeorm"; import { dataSource } from "../data-source"; import { protocolPresence } from "../entity/protocolPresence"; import InternalException from "../exceptions/internalException"; import ProtocolPresenceService from "../service/protocolPrecenseService"; import { SynchronizeProtocolPresenceCommand } from "./protocolPresenceCommand"; export default abstract class ProtocolPresenceCommandHandler { /** * @description sync protocolPresence * @param {SynchronizeProtocolPresenceCommand} * @returns {Promise} */ static async sync(syncProtocolPresences: SynchronizeProtocolPresenceCommand): Promise { let currentPresence = (await ProtocolPresenceService.getAll(syncProtocolPresences.protocolId)).map( (r) => r.memberId ); return await dataSource.manager .transaction(async (manager) => { let newMembers = syncProtocolPresences.memberIds.filter((r) => !currentPresence.includes(r)); let removeMembers = currentPresence.filter((r) => !syncProtocolPresences.memberIds.includes(r)); await this.syncPresenceAdd(manager, syncProtocolPresences.protocolId, newMembers); await this.syncPresenceRemove(manager, syncProtocolPresences.protocolId, removeMembers); }) .then(() => {}) .catch((err) => { throw new InternalException("Failed saving user roles", err); }); } private static async syncPresenceAdd( manager: EntityManager, protocolId: number, memberIds: Array ): Promise { return await manager .createQueryBuilder() .insert() .into(protocolPresence) .values( memberIds.map((m) => ({ protocolId, memberIds: m, })) ) .execute(); } private static async syncPresenceRemove( manager: EntityManager, protocolId: number, memberIds: Array ): Promise { return await manager .createQueryBuilder() .delete() .from(protocolPresence) .where("memberId IN (:...ids)", { ids: memberIds }) .andWhere("protcolId = :protocolId", { protocolId }) .execute(); } }