-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax-cached-data.html
369 lines (353 loc) · 12.7 KB
/
ajax-cached-data.html
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-ajax/iron-ajax.html">
<!--
Element to interact with the a json API and cache responses. Currently somewhat customized to only post json, and append an apikey: property to all request params.
Example:
<ajax-cached-data api-key="MyApiKey" endpoint="http://localhost/api" method-url="/get/data/" parameters='{"id": "123"}'></ajax-cached-data>
@demo demo/index.html
@hero hero.svg
-->
<dom-module id="ajax-cached-data">
<template>
<iron-ajax id="ajax" url="[[_url]]" loading="{{loading}}" body="[[_requestBody]]" content-type="application/json" handle-as="json" method="post" on-response="_handleResponse" active-requests="{{_activeRequests}}" last-response="{{_response}}"></iron-ajax>
</template>
<script>
Polymer({
is: 'ajax-cached-data',
properties: {
/**
* API Endpoint URL: ex http://localhost/api
* do not end in /
*/
endpoint: {
type: String,
},
/**
* URL part after endpoint for particular method
* ex: /get/user
*/
methodUrl: String,
/**
* api key to send with request
*/
apiKey: String,
/**
* if true will use sessionstorage, if false localstorage
*/
useSession: {
type: Boolean,
value: true
},
/**
* time for cache to expire in milliseconds (seconds * 1000)
* set to 0 if you do not want to cache responses
* default is 10 minutes
*/
cacheLife: {
type: Number,
value: 600000
},
/**
* Json object containing all the api parameters needed (but not api key)
*/
parameters: {
type: Object,
value: {}
},
/**
* If true then multiple iron-ajax requests will be sent. Otherwise it will check for an inprogress request and stop.
*/
allowMultipleRequests: {
type: Boolean,
value: false
},
/**
* Mirrors loading from iron-ajax
*/
loading: {
type: Boolean,
notify: true
},
/**
* Error messages from caching subsystem
*/
cacheErrorMessage: {
type: String,
notify: true
},
/**
* Prefix for all session or local storage keys. Default is element name ajax-cached-data
*/
storageKeyPrefix: {
type: String,
value: 'ajax-cached-data-'
},
// private
/**
* Computed url which combines endpoint and methodUrl
*/
_url: {
type: String,
computed: '_getUrl(endpoint, methodUrl)'
},
/**
* identifier string for storage key based off the method url and the api key
*/
_storageKey: {
type: String,
computed: '_getStorageKey(storageKeyPrefix, methodUrl, apiKey)'
},
/**
* object containing the cached response
*/
_cachedResponse: {
type: Object,
notify: true
},
//Subrata
_cachedResponseValue: {
type: Object,
notify: true
},
/**
* json body of ajax request. Generated from api key plus the parameters provided
*/
_requestBody: {
type: Object,
computed: '_getRequestBody(parameters, apiKey)'
},
/**
* access the active-requests property of the local iron-ajax element
*/
_activeRequests: {
type: Number,
notify: true
},
/**
* Mirrors response from iron-ajax
*/
_response: {
type: Object,
notify: true
},
/**
* "Private" access to the request generated, mostly for debugging.
*/
_lastRequest: {
type: Object,
notify: true
},
},
// Element Behavior
/**
* Makes api request. Fires response event and passes last-response to that.
* @return {boolean} True if ran successfully, false if request not made.
*/
getData: function () {
// reject multiple requests based on property
if (!this.allowMultipleRequests && this._activeRequests > 0) {
return false;
}
if (!this.apiKey) {
console.error('API key required for to make API request.');
return false;
}
if (!this._url) {
console.error('API call attempted without endpoint url and method.')
return false;
}
if (this._cacheLoad()) {
// cache hit
this.fire('ajax-cached-data-response', { "data": JSON.parse(this._cachedResponse.data), "cache": true, "timestamp": this._cachedResponse.timestamp });
// indicate success
return true;
}
else {
// cache miss, fire ajax request, save request object to property.
this._lastRequest = this.$.ajax.generateRequest();
// indicate success
return true;
}
},
/**
* Clears any cached responses.
*/
clearCache: function () {
try {
if (this.useSession) {
window.sessionStorage.removeItem(this._storageKey);
}
else {
window.localStorage.removeItem(this._storageKey);
}
}
catch (ex) {
// Happens in Safari incognito mode,
this.cacheErrorMessage = ex.message;
// fire event notifying of error so can show a user a dialog, etc, if desired.
this.fire('ajax-cached-data-cache-error', { "exception": ex });
console.error((this.useSession ? 'session' : 'local') + "Storage could not be saved. Safari incoginito mode?", ex);
}
},
// private methods
/**
* Determine if the cached data is valid based on current object properties and expires time.
*/
_cacheValidate: function (cachedObject) {
if (cachedObject &&
(!cachedObject.parameters ||
(JSON.stringify(cachedObject.parameters) == JSON.stringify(this.parameters))
) &&
cachedObject.expires > this._getTimeStamp() &&
cachedObject.url == this._url &&
cachedObject.data != null
) {
return true;
}
return false;
},
/**
* Loads the current _storageKey from window.*Storage as specified in useSession into this._cachedResponse
* @return {boolean} true if load was successful.
*/
_cacheLoad: function () {
var cachedObject;
if (this.useSession) {
cachedString = window.sessionStorage.getItem(this._storageKey);
} else {
cachedString = window.localStorage.getItem(this._storageKey);
}
if (cachedString) {
// deserialize cache data
cachedObject = JSON.parse(cachedString);
// check that cache data is valid against the element's current property states
if (!this._cacheValidate(cachedObject)) {
// dump cache and return false if not valid - example the parameters changed.
this.clearCache();
return false;
}
// put json object into _cachedResponse property
this._cachedResponse = cachedObject;
return true;
}
return false;
},
/**
* Saves data to cache
*
* todo: could caching be added in as a behavior?
* data about the cache needs to be independent of the element persistance so...
* structure of cached object is as follows:
* { "data": {data}, "url": {this._url}, "parameters": {parameters}, "expires:" {responseTimestamp + this._cacheLife} }
* api key changes are taken care of by using it in the storage key name.
* @param {object} data JSON object to be saved in the cache using this._storageKey
* @param {number} responseTimestamp when the response was received. Saved to the _cachedTime property but passed in so the _cacheSave function can manage all the cached properties itself.
*/
_cacheSave: function (data, responseTimestamp) {
// remove old data if we are calling save.
this.clearCache();
var cachedObject = { "data": data, "url": this._url, "parameters": this.parameters, "timestamp": responseTimestamp, "expires": this.cacheLife + responseTimestamp };
try {
if (this.useSession) {
window.sessionStorage.setItem(this._storageKey, JSON.stringify(cachedObject));
} else {
window.localStorage.setItem(this._storageKey, JSON.stringify(cachedObject));
}
}
catch (ex) {
// Happens in Safari incognito mode,
this.cacheErrorMessage = ex.message;
this.fire('ajax-cached-data-cache-error', { "exception": ex });
console.error(this.useSession ? "session" : "local" + "Storage could not be saved. Safari incoginito mode?", ex);
return false;
}
return true;
},
/**
* Computed method for url property
* @param {string} this.endpoint's value
* @param {string} this.methodUrl's value
* @return {string} url that can pass to the internal iron-ajax
*/
_getUrl: function (endpoint, methodUrl) {
return endpoint + methodUrl;
},
/**
* Generates a string identifier for the storage key
* changes / in method url to -
* if you change method urls then it will cache with different keys - so you *could* use this element for multiple methods if you are brave.
*/
_getStorageKey: function (storageKeyPrefix, methodUrl, apiKey) {
return storageKeyPrefix + apiKey + methodUrl.replace(/\//g, "-");
},
/**
* Combines the parametes the the supplied api key
*/
_getRequestBody: function (parameters, apiKey) {
if (parameters == null) {
parameters = {};
}
var jsonString, ajaxBody;
try {
// if params is a string leave it alone otherwise stringify it
jsonString = typeof parameters == "string" ? parameters : JSON.stringify(parameters);
// parse to an object so we don't change the original parameters instance with a new key
ajaxBody = JSON.parse(jsonString);
} catch (err) {
console.error("Invalid parameters JSON: " + err.message);
ajaxBody = {};
}
// append API key to parameters.
ajaxBody['apikey'] = apiKey;
return ajaxBody;
},
/**
* Gets timestamp. compatible if browsers do not support Date.now()
*/
_getTimeStamp: function () {
if (!Date.now) {
Date.now = function () { return new Date().getTime(); }
}
return Date.now();
},
/**
* Event handler for iron-ajax's response.
*/
_handleResponse: function () {
var cacheObj = {};
var responseTimestamp = this._getTimeStamp();
try {
cacheObj = JSON.stringify(this._response);
this._cacheSave(JSON.stringify(this._response), responseTimestamp);
}
catch (ex) {
console.error('Could not write invalid object to cache: ' + ex.message);
}
this.fire('ajax-cached-data-response', { "data": this._response, "cache": false, "timestamp": responseTimestamp });
}
// event documentation
/**
* The `ajax-cached-data-response` event is fired whenever a response is received from the API. The response data is in a key called `data`.
*
* @event ajax-cached-data-response
* @detail {{data: Object, cache: Boolean, timestamp: Number}}
*/
/**
* The `ajax-cached-data-cache-error` event is fired when the catch block is hit around a save/load in cache.
* This can be caused by safari running in private browsing mode or a browser that does not support local or sessionStorage apis.
*
* @event ajax-cached-data-cache-error
* @detail {ex: Object}
*/
});
</script>
</dom-module>