六、从零模拟新浪微博-创建微博
代码仓库:https://github.com/changeclass/koa2-weibo
数据模型
1 | /** |
在模型入口文件创建外键关系
1 | /** |
创建微博API
路由层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23/**
* @description: 首页 api 路由
* @author: 小康
* @url: https://xiaokang.me
* @Date: 2020-12-18 16:36:31
* @LastEditTime: 2020-12-18 16:36:31
* @LastEditors: 小康
*/
const router = require('koa-router')()
const { create } = require('../../controller/blog-home')
const { loginCheck } = require('../../middlewares/loginChecks')
router.prefix('/api/blog')
// 创建微博
router.post('/create', loginCheck, async (ctx, next) => {
const { content, image } = ctx.request.body
const { id: userId } = ctx.session.userInfo
ctx.body = await create({ userId, content, image })
})
module.exports = router控制器层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33/**
* @description: 首页 controller
* @author: 小康
* @url: https://xiaokang.me
* @Date: 2020-12-18 16:46:39
* @LastEditTime: 2020-12-18 16:46:39
* @LastEditors: 小康
*/
const { createBlogFailInfo } = require('../model/ErrorInfo')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { createBlog } = require('../services/blog')
/**
* @author: 小康
* @url: https://xiaokang.me
* @param {string} userId
* @param {string} content
* @param {string} image
* @description: 创建微博
*/
async function create({ userId, content, image }) {
// servers
try {
const blog = await createBlog({ userId, content, image })
return new SuccessModel(blog)
} catch (error) {
console.error(error.message, error.stack)
return new ErrorModel(createBlogFailInfo)
}
}
module.exports = { create }服务层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30/**
* @description: 微博servers
* @author: 小康
* @url: https://xiaokang.me
* @Date: 2020-12-18 16:48:09
* @LastEditTime: 2020-12-18 16:48:09
* @LastEditors: 小康
*/
const { Blog } = require('../db/model/index')
/**
* @author: 小康
* @url: https://xiaokang.me
* @description: 创建微博
* @param {string} userId
* @param {string} content
* @param {string} image
*/
async function createBlog({ userId, content, image }) {
const result = await Blog.create({
userId,
content,
image
})
return result.dataValues
}
module.exports = {
createBlog
}
防止xss攻击
安装插件
1 | yarn add xss |
对需要防止的内容进行包装即可
1 | const xss = require('xss') |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooWaline