Files
autoAiWorkSys/api/middleware/dbProxy.js
张成 5d7444cd65 1
2025-11-24 13:23:42 +08:00

76 lines
1.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const Framework = require('../../framework/node-core-framework');
/**
* 数据库代理模块
* 提供统一的数据库模型访问接口延迟获取models
*/
class DbProxy {
constructor() {
this._models = null;
}
/**
* 获取models实例
* @returns {object} models对象
*/
get models() {
if (!this._models) {
try {
this._models = Framework.getModels();
} catch (error) {
console.warn('无法获取models请确保框架已正确初始化:', error.message);
this._models = {};
}
}
return this._models;
}
/**
* 获取指定的模型
* @param {string} modelName 模型名称
* @returns {object} 模型实例
*/
getModel(modelName) {
const models = this.models;
if (!models[modelName]) {
throw new Error(`模型 '${modelName}' 不存在`);
}
return models[modelName];
}
/**
* 获取所有模型
* @returns {object} 所有模型对象
*/
getAllModels() {
return this.models;
}
/**
* 检查模型是否存在
* @param {string} modelName 模型名称
* @returns {boolean} 是否存在
*/
hasModel(modelName) {
return !!this.models[modelName];
}
/**
* 获取模型列表
* @returns {array} 模型名称列表
*/
getModelNames() {
return Object.keys(this.models);
}
/**
* 重新加载模型(在框架重新初始化后调用)
*/
reload() {
this._models = null;
}
}
// 导出单例实例
module.exports = new DbProxy();