report.js
1.77 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Created by Tommy Huang on 18/04/17.
*/
const config = require('config-lite')({
config_basedir: __dirname,
config_dir: 'config'
})
const uuid = require('uuid')
const Helper = require('./helper')
const User = require('../models').User
const BorrowList = require('../models').BorrowList
const Report = require('../models').Report
exports.create = async (req, res) => {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const kind = req.body.kind
const content = req.body.content
const imgs = req.files || []
if (!id || !kind) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, borrowList] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({where: {id: id}})
])
if (!user) throw new Error('用户不存在')
if (!borrowList || (borrowList.creditorId !== user.id && borrowList.borrowerId !== user.id )) throw new Error('借条不存在')
let imgSrc = []
if (imgs.length) {
imgSrc = await Promise.all(imgs.map(async (item) => {
let fileName = `${uuid()}.${item.mimetype.split('/')[1]}`
let buffer = item.buffer
if (buffer.size >= 2000000) {
buffer = await Helper.imageCompression(item.buffer, 1200)
}
await Helper.writeFile(`${config.img.reportImg}/${fileName}`, buffer)
return fileName
}))
}
imgSrc = imgSrc.join(',')
let report = await Report.create({
borrowListId: id,
userId: userId,
kind: kind,
content: content,
imgs: imgSrc
})
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}