iou.js
2.4 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
63
64
65
66
67
68
69
70
71
72
73
/**
* Created by Tommy Huang on 18/04/02.
*/
const config = require('config-lite')({
config_basedir: __dirname,
config_dir: 'config'
})
const moment = require('moment')
const uuid = require('uuid/v4')
const Helper = require('./helper')
const User = require('../models').User
const BorrowList = require('../models').BorrowList
const Redis = require('../models/redis')
exports.create = async function(req, res) {
try {
const idFromToken = req.user.userId
const id = req.body.userId
const amount = parseInt(req.body.amount) || 0
const role = req.body.role
const target = req.body.target
const start = req.body.start
const end = req.body.end
const rate = req.body.rate
const rateValue = parseFloat(req.body.rateValue)
const usage = req.body.usage
const explanation = req.body.explanation || ''
const imgs = req.files || []
if (!id || !role || !target || !start || !end || !rate || !rateValue || !usage ||!amount) throw new Error('参数错误')
if (idFromToken !== id) throw new Error('token check fail')
if (amount <= 0) throw new Error('非法的借款金额')
if (parseInt(rate.slice(0, rate.length - 1)) !== rateValue * 100 || rateValue < 0.01 || rateValue > 0.24) throw new Error('非法利率参数')
const startDate = moment(start)
const endDate = moment(end)
if (!(startDate.isBefore(endDate))) throw new Erro('还款日期最早为借款日期后一日')
const user = await User.findOne({where: {id: id}})
if (!user) throw new Erro('用户不存在')
let imgSrc = await Promise.all(imgs.map(async (item) => {
let fileName = `${uuid()}.${item.mimetype.split('/')[1]}`
await Helper.writeFile(`${config.img.iouImg}/${fileName}`, item.buffer)
return fileName
}))
imgSrc = imgSrc.join(',')
let newBorrowList = {
id: uuid(),
amount: amount,
startDate: startDate.utc().format(),
endDate: endDate.utc().format(),
rate: rateValue,
usage: usage,
explanation: explanation,
imgs: imgSrc,
targetName: target,
}
if (role === 'borrower') {
newBorrowList.borrowerId = user.id
} else {
newBorrowList.creditorId = user.id
}
let result = await BorrowList.create(newBorrowList)
res.json({
success: 1,
id: result.id
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `创建失败:${e.message}`
})
}
}