JSmith
JSmith

Reputation: 143

Sequelize moving class methods to individual files

This is a question based on my general lack of understanding with Node.js. I'm trying to tidy up my code, and ran into a problem.

I define a sequelize model as follows:

module.exports = (sequelize, Sequelize) => {
    // Define model
    let model= require('./lib/define')(sequelize, Sequelize);

    // Define model methods
    model.getOne = function(params) {
        return sequelize.models.model.findOne({
            include: [{
                model: sequelize.models.model2,
                include: [
                    {
                        model: sequelize.models.model3,
                        attributes: ['column1', 'column2'],
                        where: {
                            owner: params.param1,
                            name: params.param2,
                        }
                    },
                    {
                        model: sequelize.models.model4
                    }
                ]
            }],
            where: {
                // other clauses
            }
        });
    };

    return model;
};

This works fine. The model is created, I can access it across my application as well as the class based method.

However, I would like to incorporate further class based methods into this model, and to help prevent messy code, I would like to stick them in separate files. The problem is, the methods require access to the sequelize object, but I don't know how to get this into my application. I don't want to have to pass the sequelize object alongside my parameters object every time I call this method.

The current file I have for the class based method is:

module.exports = function(params) {
        return sequelize.models.model.findOne({
            include: [{
                model: sequelize.models.model2,
                include: [
                    {
                        model: sequelize.models.model3,
                        attributes: ['column1', 'column2'],
                        where: {
                            owner: params.param1,
                            name: params.param2,
                        }
                    },
                    {
                        model: sequelize.models.model4
                    }
                ]
            }],
            where: {
                // other clauses
            }
        });
    };

Upvotes: 0

Views: 305

Answers (1)

AbhinavD
AbhinavD

Reputation: 7282

From the looks of it, it looks like you need models and not the sequelize object.

You can get models object by simply requiring your models/index.js file in your helper file. Now you can excess all the models with models.model2.

For example, something like this

const models = require('../../models');
models.model2.findAll()

Upvotes: 1

Related Questions