@mini2/core
Version:
Mini Express Framework - Lightweight and modular Express.js framework with TypeScript support
68 lines • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = validationMiddleware;
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
function validationMiddleware(ValidationClass, type, logging) {
const handler = async (req, res, next) => {
try {
const source = type === 'body' ? req.body :
type === 'query' ? req.query :
type === 'headers' ? req.headers :
req.params;
if (logging) {
console.log("MINI2@CORE BODY SOURCE ORIGINAL");
console.log(source);
}
// class-transformer
const instance = (0, class_transformer_1.plainToInstance)(ValidationClass, source, {
enableImplicitConversion: true,
exposeDefaultValues: true,
});
if (logging) {
console.log("MINI2@CORE BODY SOURCE TRANSFORMED");
console.log(instance);
}
// class-validator
const errors = await (0, class_validator_1.validate)(instance, {
whitelist: true,
forbidNonWhitelisted: false,
skipMissingProperties: false,
validationError: { target: false, value: false },
});
if (errors.length > 0) {
res.status(400).json({
ok: false,
message: 'Validation error',
errors: errors.map(e => ({
property: e.property,
constraints: e.constraints,
})),
});
return; // <-- explicit return
}
Object.defineProperty(req, type, {
value: instance, // veya plain objeyi koy
writable: true,
configurable: true,
enumerable: true,
});
if (logging) {
console.log(`MINI2@CORE ASSIGNED INSTANCE TO ${type}`);
console.log(req[type]);
}
next();
return; // <-- explicit return
}
catch (err) {
res.status(400).json({
ok: false,
message: 'Validation middleware failed',
error: err?.message ?? String(err),
});
return; // <-- explicit return
}
};
return handler; // <-- handler'ı açıkça döndür
}
//# sourceMappingURL=validation.middleware.js.map