'use strict'; const BaseService = require('./base.js'); // 配置类 class ConfigsService extends BaseService { /** * [cacheKey 缓存键] * @return {[type]} [description] */ get cacheKey() { return `${process.env.APP_CUSTOME || 'universal'}_configs`; } /** * [cacheTime 缓存时间] * @return {[type]} [description] */ get cacheTime() { return 10 * 60; } /** * [getConfig 获取单行配置] * @author szjcomo * @date 2021-03-20 * @param {[type]} field_index [description] * @return {[type]} [description] */ async getConfig(field_index = null) { const that = this; const configs = await that.getConfigAll(); let result = false; configs.forEach(item => { if (item.field_index === field_index) result = item; }); return result; } /** * [getConfigValue 只获配置项的值] * @author szjcomo * @date 2021-03-20 * @param {[type]} field_index [description] * @return {[type]} [description] */ async getConfigValue(field_index = null) { const that = this; const configs = await that.getConfigAll(); let result = null; configs.forEach(item => { if (item.field_index === field_index) result = item.field_value; }); return result; } /** * [getConfigMoreValue 获取多个配置的值] * @author szjcomo * @date 2021-03-20 * @param {Array} keys [description] * @return {[type]} [description] */ async getConfigMoreValue(keys = []) { const that = this; const configs = await that.getConfigAll(); const result = {}; configs.forEach(item => { keys.forEach(childItem => { if (childItem === item.field_index) { result[childItem] = item.field_value; } }); }); return result; } /** * 获取配置的分佣比例数值 * @return {Promise} */ async getCommissionRatio() { const that = this; const config = await that.getConfigMoreValue([ 'shop_commission_ratio' ]); if (config.shop_commission_ratio) { return Number(config.shop_commission_ratio); } return 0; } /** * [getConfigGroup 获取一组配置项] * @author szjcomo * @date 2021-03-20 * @param {[type]} group [description] * @return {[type]} [description] */ async getConfigGroup(group = null) { const that = this; const configs = await that.getConfigAll(); const result = []; configs.forEach(item => { if (item.field_group === group) result.push(item); }); return result; } /** * [getConfigAll 获取所有配置] * @author szjcomo * @date 2021-03-20 * @return {[type]} [description] */ async getConfigAll() { const that = this; let result = await that.service.redis.get(that.cacheKey); if (!result) { result = await that.app.model.Configs.findAll({ attributes: { exclude: [ 'create_time', 'update_time', 'admin_id', 'field_sort', 'field_desc', 'field_options' ], }, where: { field_status: 1 }, }); if (result) await that.service.redis.set(that.cacheKey, result, that.cacheTime); } return result; } /** * [clear 清除配置缓存] * @author szjcomo * @date 2021-03-20 * @return {[type]} [description] */ async clear() { const that = this; const res = await that.service.redis.del(that.cacheKey); return res; } } module.exports = ConfigsService;