javascript - 如何扩展所有 Sequelize 模型?
问题描述
我添加了几个 Sequelize 扩展方法,db-ext.js:
module.exports = {
findResult: (filter, col = 'id') => {
filter.raw = true;
return this.findOne(filter).then(row => {
if (!row) return null;
return row[col] || null;
})
},
...
};
然后,在模型/index.js 中,我想将这些方法添加到所有模型中:
...
let sequelize;
if (configEnv.use_env_variable) {
sequelize = new Sequelize(process.env[configEnv.use_env_variable], configEnv);
} else {
sequelize = new Sequelize(configEnv.database, configEnv.username, configEnv.password, configEnv);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
//----- TODO: this one not working. What to do here, or anywhere?
Object.keys(dbExt).forEach(item => {
model[item] = dbExt[item];
})
db[model.name] = model;
});
...
启动节点时,输出错误:
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
TypeError: this.findOne is not a function
at ...
我希望我说清楚。任何帮助深表感谢!
解决方案
实现您的目标的正确方法是使用 DAOS。
为您的任何模型创建一个 dao 类。模型 A 的类的方法将是您对由模型 A 表示的表 A 执行的查询。每个类都将使用您希望派生类继承的方法显式扩展一个基 dao 类。
例如
class BaseDao {
constructor(model) {
this.model = model
}
create(data) {
return this.model.create(data);
}
findAll(options) {
return this.model.findAll(options);
}
myGreatMethod() {
// Do whatever you need
}
}
现在:
class ADao extends BaseDao {
costructor(model) {
super(model);
}
// Other great methods related to A model
}
用法:
var sequelize = require('models/index.js);
let AModel = sequelize.import('path/to/model');
let aDao = new ADao(AModel);
aDao.myGreatMethod().then().catch();
推荐阅读
- python - 滑块寻找位置 pygamemixer
- complex-event-processing - 我想自动触发脚本,无需点击输入,也无需按 Enter
- sql - 减少多值连接 SQL 查询中的重复记录
- java - 如何解决Java“嵌套循环”问题?
- c# - 尝试在 Program Files 中安装 Configuration.Save() 时访问被拒绝
- heroku - Heroku 域路由 - www 有效,没有失败
- c# - C# 构造函数不接受子类型字典
- python - 如何将原始查询集转换为查询集?
- apache-kafka - 初始化 TEST 连接器后雪花卡夫卡连接器失败
- python - 如何从嵌套循环中获取变量?