schultek / stormberry

Access your postgres database effortlessly from dart code.
https://pub.dev/packages/stormberry
MIT License
67 stars 16 forks source link

Pagination support #12

Open jaumard opened 2 years ago

jaumard commented 2 years ago

I'm used to do pagination with limit and offset, having something build in would be huge addition as of today the only way is to write the SQL.

schultek commented 2 years ago

There are limit and offset properties on the QueryParams class that you can provide to any query() method.

jaumard commented 2 years ago

Ho I miss those, but what I had in mind was a bit more generic. But it might go with a query system. The idea is that pagination is really common and you'll need it almost for all your get APIs. So having it manage by the ORM would be really nice. You define the where query, the you call a toPagination(wantedPage, limit: limit) and under the hood the ORM is doing a count to get the total number and then divide by limit to get total number of pages. Then do the request with limit and offset and return something like:

{
  "totalPages": 10,
  "data": [queried model data here],
}
jaumard commented 2 years ago

just for information that's how I did it when I tested angel3 ORM:

extension QueryExtension<T> on Query<T, QueryWhere> {
  Future<Pagination<T>> paginate(QueryExecutor executor, {int limit = kApiLimit, int page = 1}) async {
    final countItems = await count(executor);
    this
      ..limit(limit)
      ..offset((page - 1) * limit);
    final data = await get(executor);
    return Pagination(data, (countItems / limit).ceil());
  }

  Future<int> count(QueryExecutor executor) async {
    var countQuery = 'SELECT COUNT(*) FROM $tableName';
    final whereQuery = where!.compile(tableName: tableName);
    if (whereQuery.isNotEmpty) {
      countQuery += ' WHERE $whereQuery';
    }
    final result = await executor.query('not used', countQuery, {});
    return result.first.first;
  }
}

So at least I have it generic across all my API