forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
35 lines (30 loc) · 838 Bytes
/
Copy pathvalidate.js
File metadata and controls
35 lines (30 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'use strict';
const AppError = require('../errors/AppError');
function flattenZodIssues(error) {
return error.issues.reduce((fields, issue) => {
const path = issue.path.length > 0 ? issue.path.join('.') : '_root';
fields[path] = fields[path] || [];
fields[path].push(issue.message);
return fields;
}, {});
}
function validate(schema, source = 'body') {
return (req, _res, next) => {
const result = schema.safeParse(req[source] ?? {});
if (!result.success) {
return next(new AppError('VALIDATION_ERROR', 'Validation failed', 400, {
fields: flattenZodIssues(result.error),
}));
}
req.validated = {
...(req.validated || {}),
[source]: result.data,
};
req[source] = result.data;
return next();
};
}
module.exports = {
flattenZodIssues,
validate,
};