File: //proc/1233/root/home/arjun/projects/good-life-be/api/Event/validator.js
import Joi from 'joi';
import swaggerFixArrayObject from '../../helper/common.js';
export const formatTime = (time) => {
const date = new Date(`1970-01-01T${time}:00Z`);
return date.toISOString().split('T')[1].slice(0, 8); // Returns "HH:mm:ss"
};
// Validate the event ID parameter
export const validateEventId = async (req, res, next) => {
const schema = Joi.object({
id: Joi.string().required().description('The ID of the event to edit'),
});
req.params = await schema.validateAsync(req.params, {
abortEarly: false,
});
next();
};
// Validate the event ID parameter
export const validateEventQuery = async (req, res, next) => {
const schema = Joi.object({
type: Joi.string().required().description('Type'),
});
req.query = await schema.validateAsync(req.query, {
abortEarly: false,
});
next();
};
// Validator for creating an event
export const createEventValidator = async (req, res, next) => {
// req.body.start_time = formatTime(req.body.start_time);
// req.body.end_time = formatTime(req.body.end_time);
const schema = Joi.object({
event_title: Joi.string().required(),
event_description: Joi.string().allow(''),
// event_name: Joi.string().optional(),
date: Joi.date().iso().required(),
start_time: Joi.string()
// .regex(/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/) // HH:mm format
.required(),
end_time: Joi.string()
// .regex(/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/) // HH:mm format
.required(),
category: Joi.string().required(),
subCategory: Joi.string().allow(''),
}).options({ stripUnknown: true });
req.body = await schema.validateAsync(req.body, {
abortEarly: false,
});
next();
};
// Validator for editing an event
export const editEventValidator = async (req, res, next) => {
// req.body.start_time = formatTime(req.body.start_time);
// req.body.end_time = formatTime(req.body.end_time);
if (req.body.conflict !== undefined) {
req.body.conflict = req.body.conflict === 'false';
}
if (
req.body.overlapping_events !== '' &&
req.body.overlapping_events !== undefined &&
req.body.overlapping_events !== null
) {
const parsedData = JSON.parse(req.body.overlapping_events);
req.body.overlapping_events = swaggerFixArrayObject(parsedData);
} else {
req.body.overlapping_events = [];
}
const schema = Joi.object({
event_title: Joi.string().optional(),
event_description: Joi.string().allow('').optional(),
// event_name: Joi.string().optional(),
date: Joi.date().iso().optional(),
start_time: Joi.string()
// .regex(/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/) // HH:mm format
.optional(),
end_time: Joi.string()
// .regex(/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/) // HH:mm format
.optional(),
category: Joi.string().optional(),
subCategory: Joi.string().allow('').optional(),
conflict: Joi.bool().optional(),
overlapping_events: Joi.array().optional(),
}).options({ stripUnknown: true });
req.body = await schema.validateAsync(req.body, {
abortEarly: false,
});
next();
};