joukevandermaas / saule

JSON API library for ASP.Net Web API 2.
https://joukevandermaas.github.io/saule
MIT License
76 stars 37 forks source link

Pagination: Return number of pages #194

Closed bracke closed 5 years ago

bracke commented 6 years ago

Hi

Is there a way to return the "number of pages" available in the metadata? I have enabled pagination in my api using:

[Paginated(PerPage = 15, PageSizeLimit = 100)]

This works and gets me the right data and prev/next links. I would like to supplement this with information about the number of pages available.

I tried to override the GetMetadata, but the data available is the final response and thus only contains 15 items, with no way of calculating how many there are in total (?).

Is there a recommended solution for this?

Kind regards Bent Bracke

joukevandermaas commented 6 years ago

I'm sure that this is possible, but I'm not that sure it's easy :smile:. In any case Saule doesn't add this by default because we don't want to run a potentially expensive query.

If you need to get this working now, I would suggest taking a look at this feature, which should allow you to do what you need, but it's not very nice for something so simple.

Alternatively, I'm very open to extending the GetMetadata API, in particular to create a new virtual method that takes a "JSON API request context", which contains query information, the original response, the filtered response, etc. and allows people to modify the response as well as add metadata. I think this can be a very useful escape valve to have for many people.

bracke commented 6 years ago

I don't understand how "Queryable endpoints" would allow me to pass on the total pages information?

About the GetMetadata extension: Yes, that would create a lot of possibilities. I am all for it :-)

Kind regards Bent Bracke

bracke commented 5 years ago

I have solved it using the following:

in the API controller HttpContext.Current.Response.Headers.Add("total", total.ToString());

In the resource

public override object GetMetadata(object response, Type resourceType, bool isEnumerable)
{
               string totalStr = HttpContext.Current.Response.Headers["total"];
                int total = 0; if (!Int32.TryParse(totalStr, out total)) { total = 0; }

                return new
                {
                    Total = total;
                };
}