atdatabases icon indicating copy to clipboard operation
atdatabases copied to clipboard

Add the ability to an offset as well as as the limit

Open jvisker opened this issue 3 years ago • 3 comments

Without the ability to add an offset it makes it hard to do paging.

jvisker avatar Feb 28 '22 15:02 jvisker

Did you try to use native SQL query with LIMIT and OFFSET?

leandroandrade avatar Mar 08 '22 12:03 leandroandrade

I did do that, but that means it can't use some of the light ORM features that I could otherwise use.

jvisker avatar Mar 18 '22 21:03 jvisker

Just commented on @miunau's PR. I'd be very happy to see this feature added to the pg-typed & mysql-typed libraries. What you can do (which is generally more efficient, albeit not always convenient) is use the property you sort on as a pagination token.

import {greaterThan} from '@databases/pg-typed'
import db, {users} from './database'

async function paginatedUsers(pageSize: number, nextPageToken: string | null) {
  const users = 
    await users(db)
      .find(nextPageToken ? {email: greaterThan(nextPageToken)} : {})
      .orderByAsc('email')
      .limit(pageSize + 1)

  return {
    users: users.slice(0, pageSize),
    nextPageToken: users.length > pageSize ? users[pageSize - 1].email : null
  }
}

ForbesLindesay avatar Aug 02 '22 12:08 ForbesLindesay