herbsjs / herbs2knex

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

Implement find last #34

Closed maikvortx closed 2 years ago

maikvortx commented 2 years ago

Hello everyone!

We need to implement find last in herbs2knex repository, to find the last element for a query.

Describe the solution you'd like

Implement find last method with filters bellow:

Describe alternatives you've considered

async last (
    options = {
      orderBy: null,
      where: null
    }
  ) {
    options.orderBy = options.orderBy || null
    options.where = options.where || null

    const tableFields = this.dataMapper.tableFields()

    let query = this.runner().first(['timestamp', ...tableFields])

    if (!Array.isArray(options.orderBy)) options.orderBy = [options.orderBy]
    options.orderBy = [...options.orderBy, ['timestamp', 'desc']]

    return this.#executeFindQuery(query, options)
  }

Additional context

This new method uses first method to get data from data base and return the last element using timestamp to control the order of the given records.

jhomarolo commented 2 years ago

@maikvortx the knex does not have last method, so you need to use first using order by desc by the field you want

dalssoft commented 2 years ago

I wonder if the last method is necessary at all.

  1. Given the first method accept order by des|asc, you can achieve the same result.
  2. Using first method as infrastructure to last can be complicated since first method accept order by option and it can be complex with multiple fields and orders (des|asc). Trying to "reverse" the order can be trick.

A different approach is to get the last record in memory, not from the DB. But I think it is a bad UX since the firts method goes to the DB, so last should goes too.

maikvortx commented 2 years ago

Hey guys!

I agree with you. We can use a trick to get the last record for a query.