Kaltsoon / sequelize-cursor-pagination

➡️ Cursor-based pagination queries for Sequelize models
87 stars 27 forks source link

Support ordering on associated models #53

Open jadhavmanoj opened 2 years ago

jadhavmanoj commented 2 years ago

As of now, this lib does not support ordering on associated models. But this can be achieved quickly imo.

Proposed solution:

We should just look for the omitPrimaryKeyFromOrder argument, and then add primaryKeyField to the 'orderOption' variable and give that object to the model.paginate function.

We should not parse anything else. paginate parses the order argument and constructs the query.

Below code block is from normalizedOrder function - https://github.com/Kaltsoon/sequelize-cursor-pagination/blob/6d5f8ba5a241a17774bc05ad15533e854ed177de/src/utils.js#L39

We should remove this. ordering parameter for associated model can be nested many level. ex. ordering = [[{model:user, as: "users"}, "name", "ASC" ]]

 if (Array.isArray(order)) {
    normalized = order.map((o) => {
      if (typeof o === 'string') {
        return [o, 'ASC'];
      }

      if (Array.isArray(o)) {
        const [field, direction] = o;

        return [field, direction || 'ASC'];
      }

      return o;
    });
  }

Let me know if you have better approach to implement this feature.

I tried implementing this approach, worked for me.

Kaltsoon commented 2 years ago

Sounds tempting. Order normalization can't be removed (or at least it would be a very breaking change), because Sequelize's order value has many supported formats. I wonder how createCursor and recursivelyGetPaginationQuery would work in this case.

Would it be possible for you to open a pull request of your implementation with a few test cases?

jadhavmanoj commented 2 years ago

@Kaltsoon you are right! 😥. the above mentioned functions does not support ordering on associated model.

I am working on the solution. I will create PR once it is ready.