Reputation: 527
I'm trying to write some of my own validation. I've got a controller that will call several of these functions in another file. I have things like name and email.
I'm having a hard time understanding how to return a clean item or an error message. I'd like to use a promise or async-await on this but I'm running into errors.
Would be something like this
----- VALIDATE FILE
module.exports.sanitizeName = (name) => {
if(name === '' || name === null || name === undefined) {
return new Error('Name is required and cannot be null or undefined)
} else {
let cleanedName = name.toLowerCase();
return cleanedName;
}
----- CONTROLLER
const create = async (req, res) => {
let name = req.body.name;
let sanitizedName = sanitizeName(name);
// It's here that I'll need to check for an error object or the cleaned name.
// Then res.status(201).json the result or res.status(500).json the error
originally I tried a promise and ket getting unhandled errors:
--- sanitize file
let sanitizeName = (name) => {
return new Promise((resolve, reject) => {
if(happy path) {
resolve happy path (name)
} else {
reject(Error('Name is required and can't be null));
})
--- controller file
let sanitizedName = sanitizeName(name).then((result) => {
// do something here with result
}).catch((error) => {
res.status(500).json({
error_message: error
)}
Essentially I'd like to call some functions in another file and have them return a clean version of the input or an error message for validation failures.
I know express-validator and JOI exist. But I'm trying to stay away from libraries and write most of my own code.
Upvotes: 0
Views: 86
Reputation: 156
// Validation Class
module.exports.sanitizeName = (name) => {
if(name === '' || name === null || name === undefined) {
throw new Error('Name is required and cannot be null or undefined')
} else {
let cleanedName = name.toLowerCase();
return cleanedName;
}
}
// controller file
const create = async (req, res) => {
const response = {data: null, message: null, statusCode: 200}
try {
let name = req.body.name;
response.data = sanitizeName(name);
}catch (e) {
response.statusCode = 500;
response.message = e.message;
}
return res.status(response.statusCode).json(response);
}
Upvotes: 2