Files
vic-server-mongo/src/modules/fund/fund.model.js
chaosBreaking 55d77c03a3 feat:裁剪
2019-08-31 22:44:57 +08:00

68 lines
2.0 KiB
JavaScript

'use strict';
const mongoose = require('mongoose');
const ASSETTYPES = ['gin', 'vic', 'usdtBTC', 'usdtETH', 'usdtTRX'];
const FundSchema = new mongoose.Schema({
userId: {
type: String
},
tokenAddress: {
type: {},
default: {
'usdtBTC': '',
'usdtETH': '',
'usdtTRX': ''
}
},
// fund 为充值矿晶的一系列数值,用于计算收益
fund: [{
type: Number
}],
groupFundSum: {
type: Number
},
asset: {
type: {}
},
option: {
type: {}
},
}, {
timestamps: {
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
const FundModel = mongoose.model('Fund', FundSchema);
FundModel.prototype.increase = async function (assetName, amount, option = {}) {
if (!assetName || !amount || amount <= 0 || !Number.isFinite(amount) || !ASSETTYPES.includes(assetName)) return null;
const asset = 'asset.' + assetName;
const res = await FundModel.findByIdAndUpdate(this.id, {
$inc: {
[asset]: amount
}
}, { ...option, returnOriginal: false }).exec().catch(err => null);
if (!res || !res.asset) throw new Error('用户资产修改[increase]失败!');
if (res.asset[assetName] < 0) throw new Error('Insufficient funds');
return res;
};
FundModel.prototype.decrease = async function (assetName, amount, option) {
// 传入的amount应该是大于0的正数
if (!assetName || !amount || amount <= 0 || !Number.isFinite(amount) || !ASSETTYPES.includes(assetName)) return null;
amount = 0 - amount;
const asset = 'asset.' + assetName;
const res = await FundModel.findByIdAndUpdate(this.id, {
$inc: {
[asset]: amount
}
}, { ...option, returnOriginal: false }).exec().catch(err => null);
if (!res || !res.asset) throw new Error('用户资产修改[decrease]失败!');
if (res.asset[assetName] < 0) throw new Error('Insufficient funds');
return res;
};
module.exports = FundModel;