我正在创建一个Express rest API,它使用mongoose连接到MongoDB。该数据库有几种不同的数据类型:User
,Book
,Food
等。因为我正在为这些数据类型编写端点和函数。我意识到我正在重复许多相同的代码,例如,对于下面的代码:
// Book.js
import Book from './models/Book'
function deleteById (req, res, next) {
Book.findByIdAndRemove(req.params.id, function (err) {
if (err) {
let error = new Error('Failed to delete an book in database')
error.statusCode = 500
return next(error)
}
res.json({
success: true,
message: 'Book deleted successfully'
})
})
}
我可以将Book
更改为User
或Food
,并且可以使用相同的代码。这导致很多重复的代码看起来像这样:
// Food.js
import Food from './models/Food'
function deleteById (req, res, next) {
Food.findByIdAndRemove(req.params.id, function (err) {
if (err) {
let error = new Error('Failed to delete an food in database')
error.statusCode = 500
return next(error)
}
res.json({
success: true,
message: 'Food deleted successfully'
})
})
}
所以我想知道是否有办法生成函数,这样我就不需要为每种类型的数据重复deleteById
函数的代码。什么是最佳做法?或者尝试生成函数并重复是不是一种不好的做法?
任何帮助都会非常感谢,提前谢谢。
答案 0 :(得分:1)
您可以创建删除中间件。在下面的代码中,我将模型delete function
传递为argument
,然后返回一个中间件。在该中间件功能中,我调用动态发送的删除function
。
var deleteMiddleWare = function(deleteByIdFunc, name) {
var deleteId = req.params.id;
if (!deleteId)
res.json({
success: false,
message: `Please provide ${name} id.`
})
return function(req, res, next) {
deleteByIdFunc(req.params.id, function(err) {
if (err) {
let error = new Error(`Failed to delete ${name} in database`)
error.statusCode = 500
return next(error)
}
res.json({
success: true,
message: `${name} deleted successfully`
})
})
}
}
router.get(/user/delete /: id, deleteMiddleWare(User.deleteById, 'User'))
router.get(/food/delete /: id, deleteMiddleWare(Food.deleteById, 'Food'))
答案 1 :(得分:0)
经过大量研究后,我找到了使用类构造函数并将数据类型作为变量传递的最佳方法:
class BaseController {
constructor (type, name) {
if (!type || !access) {
throw new Error('Must define datatype')
}
this.datatype = type
this.name = name
this.deleteById = this.deleteById.bind(this)
}
deleteById (req, res, next) {
let name = this.name
this.datatype.findByIdAndRemove(id, function (err) {
if (err) {
let error = new Error(`Failed to delete ${name} in database`)
error.statusCode = 500
return next(error)
}
res.json({
success: true,
message: `${name} deleted successfully`
})
})
}
}
在路由器文件中,我们可以调用
const food = new BaseController(Food, 'Food')
router.get('/food/delete/:id', food.deleteById)