Skip to content

Extend Find Options and Query Builder functionality #2100

@pleerock

Description

@pleerock

The following code:

const qb = this.manager.createQueryBuilder(PostEntity, "post");

        if (filter.tagIds && filter.tagIds.length > 0)
            qb.innerJoin("post.tags", "tags", "tags.id IN (:...tagIds)")
                .setParameters({ tagIds: filter.tagIds });

        if (filter.conceptType)
            qb.innerJoin("post.tags", "tags", "tags.conceptType = :conceptType")
                .setParameters({ conceptType: filter.conceptType });

        if (filter.keyword)
            qb.andWhere("post.name ILIKE :name", { name: "%" + filter.keyword + "%" });

        if (filter.skipIds && filter.skipIds.length > 0)
            qb.andWhere("post.id NOT IN (:...skipIds)", { skipIds: filter.skipIds });

        if (filter.sortBy === "my" && this.sessionUser)
            qb.andWhere("post.authorId = :userId", { userId: this.sessionUser.personId });

        switch (filter.sortBy) {
            case "last":
                qb.orderBy("post.id", "DESC");
                break;
            case "popular":
                qb.orderBy("post.widgetCounter.score", "DESC");
                break;
            case "active":
                qb.orderBy("post.lastActiveDate", "DESC");
                break;
            default:
                qb.orderBy("post.id", "DESC");
        }

        if (filter.offset)
            qb.skip(filter.offset);

        if (filter.limit)
            qb.take(filter.limit);

        return qb;

can be translated into:

        return this.manager
            .createQueryBuilder(PostEntity, "post")
            .where({
                tags: {
                    id: If(filter.tagIds && filter.tagIds.length > 0, In(filter.tagIds)),
                    conceptType: If(filter.conceptType, filter.conceptType),
                },
                name: If(filter.keyword, Like("%" + filter.keyword + "%")),
                id: If(filter.skipIds && filter.skipIds.length > 0, Not(In(filter.skipIds))),
                authorId: If(this.sessionUser, this.sessionUser.personId)
            })
            .orderBy(Switch(filter.sortBy, {
                last: { id: "DESC" },
                popular: { widgetCounter: { score: "DESC" } },
                active: { lastActiveDate: "DESC" },
                _: { id: "DESC" },
            }))

This functionality is an extension of find options and will work with find operators as well.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions