50 lines
1.6 KiB
JavaScript
50 lines
1.6 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateBody = validateBody;
|
|
exports.validateQuery = validateQuery;
|
|
exports.validateParams = validateParams;
|
|
function sendValidationError(res, error) {
|
|
const first = error.issues[0];
|
|
const message = first?.message ?? 'Invalid request';
|
|
res.status(400).json({ error: message });
|
|
}
|
|
/**
|
|
* Validates `req.body` against a Zod schema and replaces it with parsed output.
|
|
* Returns 400 with a generic message (no field-level leak in production responses).
|
|
*/
|
|
function validateBody(schema) {
|
|
return (req, res, next) => {
|
|
const result = schema.safeParse(req.body);
|
|
if (!result.success) {
|
|
sendValidationError(res, result.error);
|
|
return;
|
|
}
|
|
req.body = result.data;
|
|
next();
|
|
};
|
|
}
|
|
/** Validates `req.query` and replaces it with coerced, typed output. */
|
|
function validateQuery(schema) {
|
|
return (req, res, next) => {
|
|
const result = schema.safeParse(req.query);
|
|
if (!result.success) {
|
|
sendValidationError(res, result.error);
|
|
return;
|
|
}
|
|
req.query = result.data;
|
|
next();
|
|
};
|
|
}
|
|
/** Validates `req.params` and replaces it with parsed output. */
|
|
function validateParams(schema) {
|
|
return (req, res, next) => {
|
|
const result = schema.safeParse(req.params);
|
|
if (!result.success) {
|
|
sendValidationError(res, result.error);
|
|
return;
|
|
}
|
|
req.params = result.data;
|
|
next();
|
|
};
|
|
}
|
|
//# sourceMappingURL=validate.js.map
|