首页 > 解决方案 > 如何扩展所有 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 ...

我希望我说清楚。任何帮助深表感谢!

标签: javascriptobjectsequelize.jsextend

解决方案


实现您的目标的正确方法是使用 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();

推荐阅读