Files
sf-sim/packages/sim-consumidor-objenious/aplication/Sim.controller.ts

99 lines
2.6 KiB
TypeScript

import { EventBus } from "#shared/domain/EventBus.port";
import { ConsumeMessage } from "amqplib";
import { SimUseCases } from "./Sim.usecases";
import { SimEvents } from "#shared/domain/SimEvents";
/**
* La clase usa generadores de funciones para mantener el contexto
* el proceso se hace en 2 partes:
* Controlador - handlers -> Router -> Ejecucion
*
*/
export class SimController {
private eventBus: EventBus;
private useCases: SimUseCases
constructor(
eventBus: EventBus,
useCases: SimUseCases
) {
this.eventBus = eventBus
this.useCases = useCases
}
private decodeMsg(msg: ConsumeMessage): object | undefined {
if (msg.content == undefined) {
console.warn('[Sim.controller] Mensaje vacío');
return undefined;
}
try {
// Convertir el Buffer a String (UTF-8)
const contentJson = JSON.parse(Buffer.from(msg.content).toString('utf8'))
return contentJson;
} catch (error) {
console.error('Error al decodificar JSON:', error);
// Aquí podrías decidir devolver el string crudo o null
return undefined;
}
}
public activateSim() {
return async (msg: ConsumeMessage) => {
if (!this.validateActivationMsg(msg)) {
throw new Error("Error consumiendo el mensaje no es valido")
}
const msgData = this.decodeMsg(msg) as SimEvents.activation
if (msgData == undefined || msgData.payload == undefined) Promise.reject("Mensaje invalido")
console.log("Mensaje procesado", msgData?.toString())
// TODO: Añadir un validador del mensaje
const iccid = msgData.payload.iccid
try {
// Caso de uso de activaciones
await this.useCases.activate({
dueDate: this.genDueDate(2 * 60).toISOString(),
identifier: {
identifierType: "ICCID",
identifiers: [iccid]
}
})()
this.eventBus.ack(msg)
} catch (e) {
this.eventBus.nack(msg)
}
}
}
public pauseSim() {
return async (msg: ConsumeMessage) => {
if (!this.validateActivationMsg(msg)) {
throw new Error("Error consumiendo el mensaje no es valido")
}
const msgData = this.decodeMsg(msg)
if (msgData == undefined) Promise.reject("Mensaje invalido")
console.log("Mensaje procesado", String(msgData))
}
}
/**
* TODO:
* - Loguear motivos de la no validacion
*/
private validateActivationMsg(msg: ConsumeMessage | null) {
if (msg == undefined) return false;
return true;
}
private genDueDate(secondsDue: number) {
const now = Date.now() + secondsDue * 1000
const dueDate = new Date(now)
return dueDate
}
}