herbsjs / herbs2knex

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

Implementation of FindWithPages #14

Closed maikvortx closed 3 years ago

maikvortx commented 3 years ago

Hi!

I'm implementing findWithPages using knex builder. I will open Pull Request!


/** 
  *
  * Find data using pagination
  * 
  * @param {type}   object.limit Limit items to list
  * @param {type}   object.offset List items offset
  * @param {type}   object.orderBy Order by query
  *
  * @return {type} List of entities
  */
  async findWithPage(options = {
    orderBy: [],
    offset: 1,
    limit: 10
  }) {

    options.orderBy = options.orderBy || []
    options.offset = options.offset || 1
    options.limit = options.limit || 10

    const tableFields = this.dataMapper.tableFields()

    if (!options.orderBy || typeof options.orderBy === "object" && !Object.keys(options.orderBy)) throw "order by is invalid"

    let query = this.runner
      .select(tableFields)

    if (options.offset > 0) query = query.offset(options.offset)
    if (options.limit > 0) query = query.limit(options.limit)
    if (!isEmpty(options.orderBy)) query = query.orderBy(options.orderBy)

    const entities = []
    const ret = await query

    for (const row of ret) {
      if (row === undefined) continue
      entities.push(this.dataMapper.toEntity(row))
    }

    let count = await this.runner
      .count('* as count')
      .first()

    return {
      total: count,
      per_page: options.limit,
      to: offset + entities.length,
      last_page: Math.ceil(count / options.limit),
      current_page: page,
      from: options.offset,
      data: entities
    }
  }
maikvortx commented 3 years ago

Implementation of findWithPages: https://github.com/maikmb/herbs2knex/tree/feature/find-with-pagination

dalssoft commented 3 years ago

How is it different from findAll with limit and offset options?

https://github.com/herbsjs/herbs2knex/issues/11

maikvortx commented 3 years ago

Hello @dalssoft! In this case, the return data is different from findAll. I think that separating the methods is the best option to implement pagination.

dalssoft commented 3 years ago

Can we close this issue after PR https://github.com/herbsjs/herbs2knex/pull/13?