How to correctly use PagedResourcesAssembler from Spring Data?

前端 未结 3 666
梦如初夏
梦如初夏 2020-11-29 17:33

I\'m using Spring 4.0.0.RELEASE, Spring Data Commons 1.7.0.M1, Spring Hateoas 0.8.0.RELEASE

My resource is a simple POJO:

public class UserResource e         


        
3条回答
  •  长情又很酷
    2020-11-29 18:18

    ALTERNATIVE WAY

    Another way is use the Range HTTP header (read more in RFC 7233). You can define HTTP header this way:

    Range: resources=20-41
    

    That means, you want to get resource from 20 to 41 (including). This way allows consuments of API receive exactly defined resources.

    It is just alternative way. Range is often used with another units (like bytes etc.)

    RECOMMENDED WAY

    If you wanna work with pagination and have really applicable API (hypermedia / HATEOAS included) then I recommend add Page and PageSize to your URL. Example:

    http://host.loc/articles?Page=1&PageSize=20
    

    Then, you can read this data in your BaseApiController and create some QueryFilter object in all your requests:

    {
        var requestHelper = new RequestHelper(Request);
    
        int page = requestHelper.GetValueFromQueryString("page");
        int pageSize = requestHelper.GetValueFromQueryString("pagesize");
    
        var filter = new QueryFilter
        {
            Page = page != 0 ? page : DefaultPageNumber,
            PageSize = pageSize != 0 ? pageSize : DefaultPageSize
        };
    
        return filter;
    }
    

    Your api should returns some special collection with information about number of items.

    public class ApiCollection
    {
        public ApiCollection()
        {
            Data = new List();
        }
    
        public ApiCollection(int? totalItems, int? totalPages)
        {
            Data = new List();
            TotalItems = totalItems;
            TotalPages = totalPages;
        }
    
        public IEnumerable Data { get; set; }
    
        public int? TotalItems { get; set; }
        public int? TotalPages { get; set; }
    }
    

    Your model classes can inherit some class with pagination support:

    public abstract class ApiEntity
    {
        public List Links { get; set; }
    }
    
    public class ApiLink
    {
        public ApiLink(string rel, string href)
        {
            Rel = rel;
            Href = href;
        }
    
        public string Href { get; set; }
    
        public string Rel { get; set; }
    }
    

提交回复
热议问题