herbsjs / herbs2knex

Create repositories using Knex to retrieve and store Entities
Other
7 stars 13 forks source link

Some ideas #3

Closed endersoncosta closed 3 years ago

endersoncosta commented 4 years ago

I made this code, thinking about how to start a query builder or something, this code is an implementation of a pagination, it works, but to insert WHERE, ORDER or any other statement this code would be extremely complex.

Then I worked on a research to understand how Knex and other ORMs do that magic. I saw just the tip of the iceberg, but I think I understand how is the logic. The implementation is hard because of the amount of details.

Anyway I think we can do something simple, to cover pagination, order and these statements that don't involve logic like Where and Join, in this moment. But preparing to implement these in a second moment.

 async findAll({ pagination }) {

        const dataMapper = this.dataMapper;
        const tableIDs = dataMapper.getTableIDs();
        const tableFields = dataMapper.getTableFields();
        const countResult = await this.count();
        const totalPages = Math.ceil(countResult / pagination.pageSize);
        const pagePosition = pagination.pageSelected * pagination.pageSize;

        const sql = \`SELECT ${tableFields.join(", ")} FROM ${
          this.tableQualifiedName
        } ORDER BY ${tableIDs[0]} LIMIT $1 OFFSET $2
        ;`;

        const ret = await this.query(sql, [pagination.pageSize, pagePosition]);
        const entities = [];
        for (const row of ret.rows) {
          if (row === undefined) continue;
          this.dataMapper.load(row);
          entities.push(this.entity.fromJSON(this.dataMapper));
        }

        return { entities, totalPages };
}