Loading.....
接上篇博客,在完成了文章的创建后及获取后,接下来完成文章的更新及删除;
上思路:
文章更新:
- 获取参数:文章标识符 slug
- 获取更新内容
- 获取更新文章
- 修改文章权限验证
- 修改字段准备
- 更新数据
- 返回处理结果
- 响应数据
文章删除思路跟更新思路相似;
文章删除:
- 获取文章标识 slug
- 获取文章
- 获取当前用户信息
- 删除文章
- 响应数据
有了思路之后,我们开始逐步实现;(详细代码内容在文章底部)
接着上篇博客内容写,首先先实现文章更新步骤:
接下来实现文章删除功能:
测试;
在终端启动服务后,我们利用 Navicat 工具可以查看数据库中的文章数据;
利用 postman 工具进行文章的更新及删除测试;
详细代码:
//更新文章
module.exports.updateArticles = async (req, res, next) => {
try {
//获取参数
const { slug } = req.params
//获取更新内容
let data = req.body.article
//获取更新文章
let article = await Article.findByPk(slug, { include: Tag })
//修改文章权限验证
const loginUser = await User.findByPk(req.user.email)
if (!loginUser) {
throw new HttpException(401, '登录账号不存在!!!', "user not found!!!")
}
const authorEmail = article.userEmail
if (loginUser.email !== authorEmail) {
throw new HttpException(401, '没有修改权限(只有作者才能修改)!!!', " No permission to modify!!!")
}
//修改字段准备
const title = data.title ? data.title : article.title
const description = data.description ? data.description : article.description
const body = data.body ? data.body : article.body
// 更新数据
const updateArticle = await article.update({ title, description, body })
// 返回处理结果
article = handleArticle(updateArticle, loginUser)
// 响应数据
res.status(200)
.json({
status: 1,
message: '文章更新成功!!!',
data: article
})
} catch (err) {
next(err);
}
};
//删除文章
module.exports.deleteArticles = async (req, res, next) => {
try {
//获取文章标识 slug
const { slug } = req.params
//获取文章
let article = await Article.findByPk(slug, { include: Tag })
if (!article) {
throw new HttpException(401, '文章不存在!!!', 'The article does not exist!!!')
}
//获取当前用户信息
const loginUser = await User.findByPk(req.user.email)
if (!loginUser) {
throw new HttpException(401, '登录账号不存在!!!', "user not found!!!")
}
const authorEmail = article.userEmail
if (loginUser.email !== authorEmail) {
throw new HttpException(401, '没有删除权限(只有作者才能删除)!!!', "Only authors can delete!!!")
}
//删除文章
await Article.destroy({ where: { slug } })
//响应数据
res.status(200)
.json({
status: 1,
message: '文章删除成功!!!'
})
} catch (err) {
next(err);
}
};
未完待续......