-
Notifications
You must be signed in to change notification settings - Fork 5
/
DataCache.js
77 lines (64 loc) · 1.85 KB
/
DataCache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Constructor for DataCache.
* More info on caching: https://developers.google.com/apps-script/reference/cache/cache
*
* @param {object} cacheService - GDS caching service
* @param {Date} startDate - beggining of GDS request interval
* @param {Date} endDate - end of GDS request interval
*
* @return {object} DataCache.
*/
function DataCache(cacheService, cacheKey) {
this.service = cacheService;
this.cacheKey = cacheKey;
return this;
}
/** @const - 6 hours, Google's max */
DataCache.REQUEST_CACHING_TIME = 21600;
/** @const - 100 KB */
DataCache.MAX_CACHE_SIZE = 100 * 1024;
/**
* Gets stored value
*
* @return {String} Response string
*/
DataCache.prototype.get = function() {
var value = '';
var chunk = '';
var chunkIndex = 0;
do {
var chunkKey = this.getChunkKey(chunkIndex);
chunk = this.service.get(chunkKey);
value += (chunk || '');
chunkIndex++;
} while (chunk && chunk.length == DataCache.MAX_CACHE_SIZE);
return value;
};
/**
* Stores value in cache.
*
* @param {String} key - cache key
* @param {String} value
*/
DataCache.prototype.set = function(value) {
this.storeChunks(value);
};
DataCache.prototype.storeChunks = function(value) {
var chunks = this.splitInChunks(value);
for (var i = 0; i < chunks.length; i++) {
var chunkKey = this.getChunkKey(i);
this.service.put(chunkKey, chunks[i], DataCache.REQUEST_CACHING_TIME);
}
};
DataCache.prototype.getChunkKey = function(chunkIndex) {
return this.cacheKey + '_' + chunkIndex;
};
DataCache.prototype.splitInChunks = function(str) {
var size = DataCache.MAX_CACHE_SIZE;
var numChunks = Math.ceil(str.length / size);
var chunks = new Array(numChunks);
for (var i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size);
}
return chunks;
};