我有这些删除用户的控制器,我想实现 DRY(不要重复自己)原则并使 res json 消息动态化



我想为下面的代码实现DRY原则,该原则删除两个不同的用户,我还想根据提供给查找方法的模型细节实现动态响应

//This code here deletes the student
exports.deleteStudent = async (req, res) => {
try {
let ID = req.query.id
let exactStudent = await Student.findById(ID)
if (!exactStudent) {
return res.status(400).json({ error: "Student with the specified ID not present" })
}
await Student.findByIdAndDelete(ID);
res.status(200).json({ success: 'Student Deleted successfully ' })
} catch (error) {
throw error
}
}

//这里的代码删除教师

exports.deleteTeacher = async (req, res) => {
try {
let ID = req.query.id
let exactTeacher = await Teacher.findById(ID)
if (!exactTeacher) {
return res.status(400).json({ error: "Teacher with the specified ID not present" })
}
await Teacher.findByIdAndDelete(ID);
res.status(200).json({ error: 'Teacher Deleted successfully ' })
} catch (error) {
throw error
}
}

我理解了你的问题,你需要这样的东西:

async function deletePerson(Model, id) => {
try {
return await Model.findByIdAndDelete(id);
} catch (error) {
throw error;
}
}
// Inside the controllers
exports.deleteStudent = async (req, res) => {
try {
const deletedEntity = await deletePerson(Student, req.query.id);
if (!deletedEntity) {
return res.status(400).json({ error: "Student with the specified ID not present" })
}
res.status(200).json({ error: 'Student Deleted successfully ' })
} catch (error) {
throw error
}
}
exports.deleteTeacher = async (req, res) => {
try {
const deletedEntity = await deletePerson(Teacher, req.query.id);
if (!deletedEntity) {
return res.status(400).json({ error: "Teacher with the specified ID not present" })
}
res.status(200).json({ error: 'Teacher Deleted successfully ' })
} catch (error) {
throw error
}
}

最新更新