refactor: Phase 2 - add error handling modules and response helpers

This commit is contained in:
2026-03-28 19:01:24 -07:00
parent 6c3848102b
commit cc8073256a
4 changed files with 336 additions and 0 deletions

View File

@@ -0,0 +1,114 @@
// Response Helpers
// Standardize API response format across all routes
const { HTTP_STATUS } = require('./constants');
/**
* Success response with data
*/
function success(res, data, statusCode = HTTP_STATUS.OK) {
return res.status(statusCode).json({
success: true,
data
});
}
/**
* Success response with message
*/
function successMessage(res, message, statusCode = HTTP_STATUS.OK) {
return res.status(statusCode).json({
success: true,
message
});
}
/**
* Created response (201)
*/
function created(res, data) {
return res.status(HTTP_STATUS.CREATED).json({
success: true,
data
});
}
/**
* No content response (204)
*/
function noContent(res) {
return res.status(HTTP_STATUS.NO_CONTENT).send();
}
/**
* Error response
*/
function error(res, message, statusCode = HTTP_STATUS.INTERNAL_ERROR) {
return res.status(statusCode).json({
success: false,
error: message
});
}
/**
* Validation error response (400)
*/
function validationError(res, message) {
return res.status(HTTP_STATUS.BAD_REQUEST).json({
success: false,
error: message
});
}
/**
* Unauthorized response (401)
*/
function unauthorized(res, message = 'Unauthorized') {
return res.status(HTTP_STATUS.UNAUTHORIZED).json({
success: false,
error: message
});
}
/**
* Forbidden response (403)
*/
function forbidden(res, message = 'Forbidden') {
return res.status(HTTP_STATUS.FORBIDDEN).json({
success: false,
error: message
});
}
/**
* Not found response (404)
*/
function notFound(res, message = 'Not found') {
return res.status(HTTP_STATUS.NOT_FOUND).json({
success: false,
error: message
});
}
/**
* Conflict response (409)
*/
function conflict(res, message) {
return res.status(HTTP_STATUS.CONFLICT).json({
success: false,
error: message
});
}
module.exports = {
success,
successMessage,
created,
noContent,
error,
validationError,
unauthorized,
forbidden,
notFound,
conflict
};