Intento de mejorar el proceso de validacion de los controladores
This commit is contained in:
@@ -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
|
||||
*
|
||||
* <O> Representa el dato original
|
||||
* <P> Representa el dato después del mapeo
|
||||
*/
|
||||
public controllerGenerator<O, P>(args: {
|
||||
validator?: BodyValidator<O>,
|
||||
mapBody?: (body: O) => P,
|
||||
useCase: (args: P) => Promise<void>,
|
||||
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 })
|
||||
|
||||
|
||||
Reference in New Issue
Block a user