Tuesday, 2 May 2017

Sequelize conditional inclusion of where clause nodejs

I have this code, which has multiple where clause:

Time_Sheet_Details.findAll({
    include: [
        {
            model: timesheetNotesSubcon,
            required: false,
            attributes:["note","file_name", "id", "working_hrs", "timestamp", "has_screenshot", "notes_category"]
        },
        {
            model: Timesheet,
            attributes:["id","leads_id","userid"],
            where:  {leads_id: filters.leads_id}, // Client
            include:[
                {
                    model: Lead_Info, attributes:["id","fname","lname","email","hiring_coordinator_id","status"],
                    where:  {hiring_coordinator_id: {$in: filters.sc_id}}, // SC
                    include:[{
                        model: adminInfoSchema,
                        required: false,
                        attributes:["admin_id","admin_fname", "admin_lname", "admin_email", "signature_contact_nos", "signature_company"],      
                    }]

                },
                {
                    model:Personal_Info,attributes:["userid","fname","lname","email"],
                    where: {userid: filters.subcon_id}, // Subcon
                }
            ]
        }],
    where: { 
        reference_date: filters.reference_date
    },
    order:[
        ["id","DESC"]
    ],
    offset:((page-1)*limit),
    limit : limit,
    subQuery:false

}).then(function(foundObject){
    willFulfillDeferred.resolve(foundObject);
});

The where clause is the one with the comment Client, SC and Subcon. However, what is the best approach if those where clause is optional? I am using that for search filter. So if filters.leads_id is null then the where: {leads_id: filters.leads_id}, // Client should not be included in the query. Same with the others. The only solution I can think of is repeat those code blocks for each scenario of not null parameters but that's to repetitive and not practical.

Any other approach or solutions?



via Yassi

No comments:

Post a Comment