简体   繁体   English

您使用什么策略来获取和缓存分页集合,特别是在角度或重绘中?

[英]What strategies do you use for fetching and caching paginated collections, specifically in angular or restangular?

Let's say an app consumes data from a REST api that exposes paginated collections, and the number of items in a collection can be infinitely large (ie too many items to fetch all at once and store in a browser session). 假设一个应用程序使用暴露分页集合的REST API中的数据,并且集合中的项目数量可能无限大(即,一次获取所有项目并存储在浏览器会话中的项目太多)。

What are good strategies for fetching, caching and invalidating the cache of such data? 什么是获取,缓存和使这些数据的缓存无效的好策略?

Say, the API is like, 说,API就像,

GET /users?page=1&per_page=50

With a response like below (ie includes the collection data + paging meta data) 使用如下响应(即包括收集数据+分页元数据)

{
  "paging": {
    "per_page": 20,
    "page": 1,
    "previous": null,
    "self": "/api/v1/users?per_page=20&page=1",
    "next": "/api/v1/users?per_page=20&page=2"
  },
  "data": [
    // first 20 users
  ]
}

The client may or may not load the collection in contiguous pages, one page at a time. 客户端可能会也可能不会在连续页面中加载集合,一次一页。 The users in the collection may be changed, by any client. 任何客户端都可以更改集合中的用户。 Eventual consistency is sufficient and I'm not concerned about write conflicts at this time. 最终的一致性就足够了,我现在并不关心写冲突。

The question is in the context of an angularjs app, but is a generic scenario. 问题是在angularjs应用程序的上下文中,但是是一般的场景。

What I'd do/did is use angular's $cacheFactory and have one entry for each API endpoint. 我做/做的是使用angular的$ cacheFactory ,每个API端点都有一个条目。 So if your current URL is /api/v1/users?per_page=20&page=1 the cache's key would be /api/v1/users without any pagination parameters. 因此,如果您当前的URL是/api/v1/users?per_page=20&page=1则缓存的密钥将是/api/v1/users而没有任何分页参数。 Then once the response is returned do the following in the function which handles the data: 然后,一旦返回响应,请在处理数据的函数中执行以下操作:

// add customer insert method somewhere
Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item);
};

var cachedData = $cacheFactory.get(key);

var insertPosition = pageSize * currentPage;

cachedData.insert(insertPosition, returnedData);

$cacheFactory.put(cachedData);

Probably a lot simpler than it would have to be in a real life scenario, but you get the idea. 可能比现实生活中的情况简单得多,但你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM