Skip to content

Commit

Permalink
请求参数增加校验
Browse files Browse the repository at this point in the history
  • Loading branch information
wwervin72 committed May 6, 2020
1 parent 681518b commit c4a8ef2
Show file tree
Hide file tree
Showing 13 changed files with 14,654 additions and 5 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"rest-client.environmentVariables": {
"$shared": {},
"development": {
"contentPath": "/api",
"baseURL": "http://localhost:3000"
}
}
Expand Down
16 changes: 16 additions & 0 deletions api/article.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#@name create

POST {{baseURL}}{{contentPath}}/article HTTP/1.1

{
"title": "test",
"allow_comment": true,
"content": "",
"abstract": "",
"password": "",
"thumbnail": "",
"category": "",
"tags": "",
}

###
9 changes: 9 additions & 0 deletions api/user.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#@name create

POST {{baseURL}}/register HTTP/1.1

{
"user": ""
}

###
9 changes: 9 additions & 0 deletions app/controller/article.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { validationResult } = require('express-validator')
const models = require('../../config/db/model')
const { renderCommentListHtml, respond, respEntity } = require('../utils/index')
const sequelize = models.sequelize
Expand All @@ -13,6 +14,10 @@ exports.articleList = function (req, res, next) {
* 保存文章
*/
exports.saveArticle = function (req, res, next) {
const validatorResult = validationResult(req)
if (!validatorResult.isEmpty()) {
return respond(res, respEntity(null, 422, validatorResult.errors.map(err => err.msg).join(',')), 422)
}
let data = req.body
data.article_author = req.user.id
if (data.category) {
Expand Down Expand Up @@ -48,6 +53,10 @@ exports.saveArticle = function (req, res, next) {
* 更新
*/
exports.updateArticle = function (req, res, next) {
const validatorResult = validationResult(req)
if (!validatorResult.isEmpty()) {
return respond(res, respEntity(null, 422, validatorResult.errors.map(err => err.msg).join(',')), 422)
}
models.Article.findOne({
where: {
id: req.body.id,
Expand Down
120 changes: 120 additions & 0 deletions app/schema/article.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
const models = require('../../config/db/model')
const Sequelize = require('sequelize')

exports.create = {
title: {
in: ['body'],
isString: {
errorMessage: "文章标题必须是字符串"
},
notEmpty: {
errorMessage: "文章标题不能为空"
},
},
allow_comment: {
in: ['body'],
custom: {
options: (val, {req, location, path}) => {
if (val !== '0' && val !== '1') {
throw new Error('是否允许评论参数错误')
}
return true
}
}
},
content: {
in: ['body'],
isString: {
errorMessage: "文章内容必须是字符串"
},
notEmpty: {
errorMessage: "文章内容不能为空"
},
},
abstract: {
in: ['body'],
isString: {
errorMessage: "文章摘要必须是字符串"
},
notEmpty: {
errorMessage: "文章摘要不能为空"
},
},
password: {

},
thumbnail: {
in: ['body'],
isString: {
errorMessage: "文章密码必须是字符串"
}
},
category: {
custom: {
options: (val, {req, location, path}) => {
if (val) {
return models.Category.findUserCategories(req.user.id, {
id: {
[Sequelize.Op.in]: val
}
}).then(categories => {
let unExistedCategories = val.filter(el => categories.findIndex(t => t.id === el) === -1)
if (unExistedCategories.length) {
return Promise.reject(`分类${unExistedCategories.join(',')}不存在`)
} else {
return true
}
})
}
return true
}
}
},
'tags': {
in: ['body'],
isArray: {
errorMessage: "文章标签必须是标签数组"
},
custom: {
options: (val, {req, location, path}) => {
if (val.length) {
return models.Tag.findUserTags(req.user.id, {
id: {
[Sequelize.Op.in]: val
}
}).then(tags => {
let unExistedTags = val.filter(el => tags.findIndex(t => t.id === el) === -1)
if (unExistedTags.length) {
return Promise.reject(`标签${unExistedTags.join(',')}不存在`)
} else {
return true
}
})
}
return true
}
}
},
}

exports.update = {
...exports.create,
id: {
in: ['body'],
custom: {
options: (val, {req, location, path}) => {
if (val) {
return models.Article.queryUserArticle(req.user.id, val)
.then(a => {
if (!a) {
return Promise.reject(`文章不存在`)
} else {
return true
}
})
}
throw new Error('请传入文章 id')
}
}
}
}
3 changes: 3 additions & 0 deletions app/schema/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exports.create = {

}
10 changes: 10 additions & 0 deletions config/db/model/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,16 @@ module.exports = (sequelize, DataTypes) => {
.catch(err => Promise.reject(err))
}

Article.queryUserArticle = function (userId, articleId, attrs = ['id']) {
return Article.findOne({
where: {
article_author: userId,
id: articleId
},
attributes: attrs
})
}

Article.queryArticleEditDetail = function (models, params) {
return new Promise((resolve, reject) => {
models.Article.findOne({
Expand Down
10 changes: 10 additions & 0 deletions config/db/model/category.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,15 @@ module.exports = (sequelize, DataTypes) => {
foreignKey: 'article_category'
})
}

Category.findUserCategories = function (userId, options = {}) {
return Tag.findAll({
where: {
user: userId,
...options
},
attributes: ['id', 'name', 'desc']
})
}
return Category
}
7 changes: 5 additions & 2 deletions config/db/model/tag.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ module.exports = (sequelize, DataTypes) => {
})
}

Tag.findUserTags = function (userId) {
Tag.findUserTags = function (userId, options = {}) {
return Tag.findAll({
where: {user: userId},
where: {
user: userId,
...options
},
attributes: ['id', 'name', 'desc']
})
}
Expand Down
6 changes: 4 additions & 2 deletions config/routes.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const express = require('express')
const { checkSchema } = require('express-validator')
const pageRouter = express.Router()
const apiRouter = express.Router()

Expand All @@ -9,6 +10,7 @@ const articleCtrl = require('../app/controller/article.controller')
const pageCtrl = require('../app/controller/page.controller')
const annexCtrl = require('../app/controller/annex.controller')
const { requireSignIn, verifyIsManager, verifyLocalAccount } = require('./middleware/authorization.js')
const articleSchema = require('../app/schema/article')

module.exports = function (app, passport) {
const pauth = passport.authenticate.bind(passport)
Expand Down Expand Up @@ -75,7 +77,7 @@ module.exports = function (app, passport) {
// 上传附件
apiRouter.post('/uploadAnnex', requireSignIn, verifyLocalAccount, annexCtrl.uploadAnnex)
// 保存文章
apiRouter.post('/article', requireSignIn, verifyLocalAccount, articleCtrl.saveArticle)
apiRouter.post('/article', requireSignIn, verifyLocalAccount, checkSchema(articleSchema.create), articleCtrl.saveArticle)
// 获取 emoji 面板html
apiRouter.get('/emoji/html', pageCtrl.generateEmojiPanelHtml)
// 获取文章详情
Expand All @@ -89,7 +91,7 @@ module.exports = function (app, passport) {
// 取消点赞文章
apiRouter.delete('/article/:articleId/heart', requireSignIn, articleCtrl.cancelHeartArticle)
// 更新文章
apiRouter.put('/article', requireSignIn, verifyLocalAccount, articleCtrl.updateArticle)
apiRouter.put('/article', requireSignIn, verifyLocalAccount, checkSchema(articleSchema.update), articleCtrl.updateArticle)
// 删除
apiRouter.delete('/article', requireSignIn, verifyLocalAccount, articleCtrl.delArticle)
// blog 文章分页
Expand Down
Loading

0 comments on commit c4a8ef2

Please sign in to comment.