Home > Net >  Conditional Op.or, Op.ne and direct include in sequelize and nestjs
Conditional Op.or, Op.ne and direct include in sequelize and nestjs

Time:05-20

I have a incoming state for controller that may be draft, published of something else, Right now I am handling these three functions separately, How can I combine them together, to form a more clear code

if (state === 'published') {
            return this.checklistModelService.getAllWhere(
                { '$checklistRevision.publishedAt$': { [Op.ne]: null } },
                undefined,
                {
                    include: { model: ChecklistRevisionSchema },
                },
            );
        }

        if (state === 'draft') {
            return this.checklistModelService.getAllWhere(
                { '$checklistRevision.publishedAt$': { [Op.is]: null } },
                undefined,
                {
                    include: { model: ChecklistRevisionSchema },
                },
            );
        }

        return this.checklistModelService.getAll(undefined, {
            include: { model: ChecklistRevisionSchema },
        });

CodePudding user response:

You can do it in this way, first store the findOptions in a seperate variable and than use that in the query.

   var findOptions = {};
    
            state
                ? (findOptions = {
                        where: {
                            '$checklistRevision.publishedAt$': {
                                [state === 'published' ? Op.ne : Op.is]: null,
                            },
                        },
                        include: { model: ChecklistRevisionSchema },
                  })
                : (findOptions = {
                        include: { model: ChecklistRevisionSchema },
                  });
    
            return this.checklistModelService.getAll(undefined, findOptions);
  • Related