From 19b2958a9c8d2c72b1f4a8e28bdf04cb37ea80ef Mon Sep 17 00:00:00 2001 From: Alvar San Martin Date: Tue, 10 Feb 2026 17:26:04 +0100 Subject: [PATCH] Intento de mejorar el proceso de validacion de los controladores --- .../aplication/Sim.controller.ts | 75 ++++++++++++++++--- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/packages/sim-entrada-eventos/aplication/Sim.controller.ts b/packages/sim-entrada-eventos/aplication/Sim.controller.ts index b53c1df..4e183bc 100644 --- a/packages/sim-entrada-eventos/aplication/Sim.controller.ts +++ b/packages/sim-entrada-eventos/aplication/Sim.controller.ts @@ -2,6 +2,8 @@ import { Request, Response } from "express" import { SimUsecases } from "./Sim.usecases.js" import { activationValidator, iccidValidator } from "./httpValidators.js" import { companyFromIccid } from "#domain/companies.js" +import { BodyValidator } from "#shared/aplication/BodyValidator.js" +import assert from "node:assert" export class SimController { @@ -15,6 +17,69 @@ export class SimController { this.activation = this.activation.bind(this) } + /** + * TODO: + * En proceso, tiene varios problemas + * + * Abstrae el proceso de + * Peticion -> validacion del body -> map del body -> useCase -> OK/ERR + * + * Representa el dato original + *

Representa el dato después del mapeo + */ + public controllerGenerator(args: { + validator?: BodyValidator, + mapBody?: (body: O) => P, + useCase: (args: P) => Promise, + onError: (args: O | P, error: string) => void, + onSuccess: (args: P) => void, + }) { + return async (req: Request, res: Response) => { + const body = req.body + + // 1. Validacion del body + try { + if (args.validator != undefined) + args.validator.validate(body) + } catch (e) { + if (args.onError != undefined) args.onError(body, e as string) + res.status(422).json({ + errors: { + msg: e + } + }) + } + + // 2. Transformacion del body + let data: P = body; + try { + if (args.mapBody != undefined) + data = args.mapBody(body) + } catch (e) { + res.status(422).json({ + errors: { + msg: "Error parseando el body: " + e + } + }) + } + + // 3. Aplicacion del UseCase + try { + const usecaseResult = await args.useCase(data) + res.status(200).json( + usecaseResult + ).send() + } catch (err) { + res.status(500).json({ + errors: { + msg: "Error general:" + err + } + }).send() + return; + } + } + } + public preactivation() { return async (req: Request, res: Response) => { console.warn("[!] Se deberia de usar la peticion /sim/activate directamente") @@ -31,16 +96,6 @@ export class SimController { const { iccid } = req.body const compañia = companyFromIccid(iccid) - if (compañia == undefined) { - res.status(500).json({ - errors: { - msg: "El iccid no pertenece a una compañia conocida" - } - }) - return; - } - - try { await this.simUseCases.preActivation({ iccid, compañia })