Skip to content

Commit 2b98044

Browse files
committed
Added GetWithCount method
1 parent 9b33b65 commit 2b98044

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Postgrest/Interfaces/IPostgrestTable.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,15 @@ IPostgrestTable<TModel> Filter<TCriterion>(Expression<Func<TModel, object>> pred
119119
/// <returns></returns>
120120
Task<ModeledResponse<TModel>> Get(CancellationToken cancellationToken = default);
121121

122+
/// <summary>
123+
/// Executes the query using the defined filters on the current instance, along with count from the specified query.
124+
/// </summary>
125+
/// <param name="type">The kind of count.</param>
126+
/// <param name="cancellationToken"></param>
127+
/// <returns></returns>
128+
Task<Tuple<List<TModel>, int>> GetWithCount(Constants.CountType type,
129+
CancellationToken cancellationToken = default);
130+
122131
/// <summary>
123132
/// Executes a BULK INSERT query using the defined query params on the current instance.
124133
/// </summary>

Postgrest/Table.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,26 @@ public Task<ModeledResponse<TModel>> Get(CancellationToken cancellationToken = d
634634
Clear();
635635
return request;
636636
}
637+
638+
/// <inheritdoc />
639+
public async Task<Tuple<List<TModel>, int>> GetWithCount(CountType type, CancellationToken cancellationToken = default)
640+
{
641+
var attr = type.GetAttribute<MapToAttribute>();
642+
643+
var headers = new Dictionary<string, string>
644+
{
645+
{ "Prefer", $"count={attr?.Mapping}" }
646+
};
647+
648+
var request = Send<TModel>(_method, null, headers, cancellationToken);
649+
Clear();
650+
651+
var response = await request;
652+
var countStr = response.ResponseMessage?.Content.Headers.GetValues("Content-Range").FirstOrDefault();
653+
var count = int.Parse(countStr?.Split('/')[1] ?? throw new InvalidOperationException());
654+
655+
return new Tuple<List<TModel>, int>(response.Models, count);
656+
}
637657

638658
/// <summary>
639659
/// Generates the encoded URL with defined query parameters that will be sent to the Postgrest API.

0 commit comments

Comments
 (0)