Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
// /components/professors/professorService.js
|
|
|
|
const Professor = require('./professorModel');
|
|
const AppError = require('../../utils/AppError');
|
|
const eventEmitter = require('../../events/eventEmitter');
|
|
const EVENT_NAMES = require('../../constants/eventNames');
|
|
const { parsePaginationAndSort, buildFilterQuery, calculateMeta } = require('../../utils/pagination');
|
|
|
|
const createProfessor = async (data) => {
|
|
const existing = await Professor.findOne({
|
|
$or: [
|
|
{ nationalIdCode: data.nationalIdCode },
|
|
{ phoneNumber: data.phoneNumber },
|
|
...(data.email ? [{ email: data.email }] : [])
|
|
]
|
|
});
|
|
if (existing) {
|
|
throw new AppError('PROFESSOR_ALREADY_EXISTS');
|
|
}
|
|
|
|
const professor = await Professor.create(data);
|
|
eventEmitter.emit(EVENT_NAMES.PROFESSOR_CREATED, { professorId: professor._id, name: `${professor.name} ${professor.surname}` });
|
|
return professor;
|
|
};
|
|
|
|
const getProfessorById = async (id) => {
|
|
const professor = await Professor.findById(id).populate('courses', 'title type price');
|
|
if (!professor) {
|
|
throw new AppError('PROFESSOR_NOT_FOUND');
|
|
}
|
|
return professor;
|
|
};
|
|
|
|
const getAllProfessors = async (queryParams) => {
|
|
const { page, limit, skip, sort } = parsePaginationAndSort(queryParams);
|
|
const filter = buildFilterQuery(queryParams, ['name', 'surname', 'nationalIdCode', 'phoneNumber', 'email', 'expertise']);
|
|
|
|
const [professors, totalCount] = await Promise.all([
|
|
Professor.find(filter).populate('courses', 'title').sort(sort).skip(skip).limit(limit),
|
|
Professor.countDocuments(filter)
|
|
]);
|
|
|
|
const meta = calculateMeta(totalCount, page, limit);
|
|
return { data: professors, meta };
|
|
};
|
|
|
|
const updateProfessor = async (id, updateData) => {
|
|
const professor = await Professor.findById(id);
|
|
if (!professor) {
|
|
throw new AppError('PROFESSOR_NOT_FOUND');
|
|
}
|
|
|
|
Object.assign(professor, updateData);
|
|
await professor.save();
|
|
return professor;
|
|
};
|
|
|
|
const deleteProfessor = async (id) => {
|
|
const professor = await Professor.findById(id);
|
|
if (!professor) {
|
|
throw new AppError('PROFESSOR_NOT_FOUND');
|
|
}
|
|
|
|
await Professor.findByIdAndDelete(id);
|
|
return null;
|
|
};
|
|
|
|
const searchProfessors = async (queryParams) => {
|
|
return getAllProfessors(queryParams);
|
|
};
|
|
|
|
module.exports = {
|
|
createProfessor,
|
|
getProfessorById,
|
|
getAllProfessors,
|
|
updateProfessor,
|
|
deleteProfessor,
|
|
searchProfessors
|
|
};
|