Files
2026-03-26 22:46:03 +01:00

76 lines
2.2 KiB
JavaScript

const config = require('../config');
class ApiResponse {
constructor(success, statusCode, data = null, message = null, errors = null) {
this.success = success;
this.statusCode = statusCode;
this.data = data;
this.message = message;
this.errors = errors;
this.timestamp = new Date().toISOString();
}
toJSON() {
const response = {
success: this.success,
timestamp: this.timestamp,
};
if (this.message) response.message = this.message;
if (this.data !== null) response.data = this.data;
if (this.errors) response.errors = this.errors;
return response;
}
}
class ResponseHandler {
static success(res, data, message = 'Success', statusCode = config.HTTP_STATUS.OK) {
const response = new ApiResponse(true, statusCode, data, message);
return res.status(statusCode).json(response.toJSON());
}
static created(res, data, message = 'Resource created successfully') {
return this.success(res, data, message, config.HTTP_STATUS.CREATED);
}
static error(
res,
message,
statusCode = config.HTTP_STATUS.INTERNAL_SERVER_ERROR,
errors = null
) {
const response = new ApiResponse(false, statusCode, null, message, errors);
return res.status(statusCode).json(response.toJSON());
}
static badRequest(res, message = 'Bad request', errors = null) {
return this.error(res, message, config.HTTP_STATUS.BAD_REQUEST, errors);
}
static notFound(res, message = 'Resource not found') {
return this.error(res, message, config.HTTP_STATUS.NOT_FOUND);
}
static unauthorized(res, message = 'Unauthorized') {
return this.error(res, message, config.HTTP_STATUS.UNAUTHORIZED);
}
static forbidden(res, message = 'Forbidden') {
return this.error(res, message, config.HTTP_STATUS.FORBIDDEN);
}
static conflict(res, message = 'Resource conflict', errors = null) {
return this.error(res, message, config.HTTP_STATUS.CONFLICT, errors);
}
static internalError(res, message = 'Internal server error', error = null) {
if (error && config.isDevelopment) {
console.error('Internal Error:', error);
}
return this.error(res, message, config.HTTP_STATUS.INTERNAL_SERVER_ERROR);
}
}
module.exports = ResponseHandler;