let fspromises = require('fs').promises; import { get, cloneDeep } from 'lodash'; import { define } from '../define'; export class DynamicSetting { constructor(global) { this.global = global; } /** * 通过指定的类型,获取数据 * @param {*} type default:在代码中写死的 dynamic:用户自定义的 all:写死的和自定义的合并返回 * @param {*} mainType 主分类,gpt,tag这些 * @param {*} property 返回书信的名称 gpt_options,gpt_model_options,gpt_auto_inference * @param {*} defaultSetting 默认的设置,用于合并数据 * @param {*} defaultData 默认数据,默认值为null * @returns */ async getDataByTypeAndProperty(type, mainType, property, defaultSetting, defaultData = []) { try { let res = []; // 获取自定义的GPT数据 let dynamic_setting = JSON.parse(await fspromises.readFile(define.dynamic_setting, 'utf-8')); let tags = get(dynamic_setting, mainType, {}); let data = get(tags, property, defaultData); if (type == "default") { // res = get(this, property, defaultData); } else if (type == "dynamic") { res = data; } else if (type == "all") { res = defaultSetting.concat(data); } else { throw new Error(`不存在的类型 : ${value}`); } return { code: 1, data: res } } catch (error) { return { code: 0, message: error.toString() } } } /** * 保存 dynamic_setting 中主分支中指定属性的数据 * @param {*} value 要保存的数据 * @param {*} mainType 大的设置里面的主分支 * @param {*} property 对应的属性 * @param {*} callback 回调函数,可以对数据进行自定义的判断 */ async saveDataByTypeAndProperty(value, mainType, property, callback = null) { try { // 获取自定义的GPT数据 let dynamic_setting = JSON.parse(await fspromises.readFile(define.dynamic_setting, 'utf-8')); let tmp_gpt = get(dynamic_setting, mainType, {}); let gpt = tmp_gpt[property] ? tmp_gpt[property] : []; if (callback) { callback(gpt); } if (value.id) { // 判断当前ID的数据是否存在,存在覆盖,不存在追加 let index = gpt.findIndex(item => item.id == value.id); if (index < 0) { gpt.push(value); } else { gpt[index] = value; } } else { value.id = uuidv4(); gpt.push(value); } tmp_gpt[property] = gpt; // 将修改后的数据保存 dynamic_setting[mainType] = tmp_gpt; // 写入文件 await fspromises.writeFile(define.dynamic_setting, JSON.stringify(dynamic_setting)); } catch (error) { throw error; } } /** * 删除指定的属性中的数据 * @param {*} id 要删除数据的ID * @param {*} mainType 删除的主分支的类别 * @param {*} property 删除的属性中的数据 */ async deleteDataByTypeAndProperty(id, mainType, property) { try { // 获取自定义的GPT数据 let dynamic_setting = JSON.parse(await fspromises.readFile(define.dynamic_setting, 'utf-8')); let tmp_data = get(dynamic_setting, mainType, {}); let gpt = tmp_data[property] ? tmp_data[property] : []; // 判断当前ID的数据是否存在,存在删除 let index = gpt.findIndex(item => item.id == id); if (index >= 0) { gpt.splice(index, 1); } // 将修改后的数据保存 dynamic_setting[mainType][property] = gpt; // 写入文件 await fspromises.writeFile(define.dynamic_setting, JSON.stringify(dynamic_setting)); } catch (error) { throw error; } } }