I am posting an Express route which seems to handle all params and data as strings. I am currently having to individually convert them to Number
values and was wondering if there was a way to take care of all of them in one pass?
This is how the route looks:
Router.post('/user/:UserID',
async function (req, res, next) {
const UserID = Number(req.params.UserID);
const StatusID = Number(req.body.StatusID);
const DepartmentID = Number(req.body.DepartmentID);
...
try {
await API.getUserDetails({
DepartmentID: DepartmentID,
UserID: UserID,
StatusID: StatusID
...
});
} catch (e) {
console.error(e)
}
}
Rather than individually converting the params and data to Numbers I would like to do something like this:
Router.post('/user/:UserID',
async function (req, res, next) {
// If a value can be converted to a Number, then convert it
req = JSON.stringify(req, function (key, value) {
return Number(value) || value
});
req = JSON.parse(req, function (key, value) {
return Number(value) || value
});
try {
await API.getUserDetails({
DepartmentID: req.body.DepartmentID,
UserID: req.params.UserID,
StatusID: req.body.StatusID
...
});
} catch (e) {
console.error(e)
}
}
Obviously the above attempt does not work and I get errors like: TypeError: Cannot convert object to primitive value
.
Is this even achieveable?