/** * 基础模型类 * @file BaseModel.js * @description 所有模型的基类,提供通用方法 */ const { Model } = require('sequelize'); class BaseModel extends Model { /** * 获取模型的安全信息(排除敏感字段) * @param {Array} excludeFields 要排除的字段 * @returns {Object} 安全信息对象 */ getSafeInfo(excludeFields = ['password', 'pin', 'secret']) { const data = this.get({ plain: true }); if (Array.isArray(excludeFields)) { excludeFields.forEach(field => { delete data[field]; }); } return data; } /** * 转换为JSON格式 * @param {Array} excludeFields 要排除的字段 * @returns {Object} JSON对象 */ toJSON(excludeFields = ['password', 'pin', 'secret']) { return this.getSafeInfo(excludeFields); } /** * 格式化金额(分转元) * @param {Number} amount 金额(分) * @returns {String} 格式化后的金额 */ formatAmount(amount) { if (amount === null || amount === undefined) return '0.00'; return (amount / 100).toFixed(2); } /** * 解析金额(元转分) * @param {String|Number} amount 金额(元) * @returns {Number} 金额(分) */ parseAmount(amount) { if (typeof amount === 'string') { return Math.round(parseFloat(amount) * 100); } return Math.round(amount * 100); } /** * 格式化日期 * @param {Date} date 日期 * @param {String} format 格式 * @returns {String} 格式化后的日期 */ formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') { if (!date) return null; const moment = require('moment'); return moment(date).format(format); } /** * 检查字段是否已更改 * @param {String} field 字段名 * @returns {Boolean} 是否已更改 */ isFieldChanged(field) { return this.changed(field); } /** * 获取原始值 * @param {String} field 字段名 * @returns {*} 原始值 */ getOriginalValue(field) { return this._previousDataValues[field]; } /** * 软删除(如果模型支持) */ async softDelete() { if (this.constructor.rawAttributes.deleted_at) { this.deleted_at = new Date(); await this.save(); } else { throw new Error('模型不支持软删除'); } } /** * 恢复软删除(如果模型支持) */ async restore() { if (this.constructor.rawAttributes.deleted_at) { this.deleted_at = null; await this.save(); } else { throw new Error('模型不支持软删除'); } } } module.exports = BaseModel;