Quote:
Originally Posted by RogerKwok
Question about frontend caching objects to prevent requests:
Say user goes to "website.com/objects/1"
My JS logic is basically (we use Angular, so this'd be in service.js):
If cache[obj_1_key] doesn't exist, make request to "/api/objects/1", put the JSON response into cache.
Otherwise just serve from cache and avoid the request altogether.
Assuming the object doesn't change often (say once every week), is there a downside to this approach?
If you're using Angular, this functionality is built into $http. Look into the caching section here:
https://docs.angularjs.org/api/ng/service/$http
Even if you're not using $http's built-in caching functionality, you may want to use this:
https://docs.angularjs.org/api/ng/service/$cacheFactory
If not, you may want to create the cache object with Object.create(null) as to create an object with no built-in properties that can clash with keys. This is normally not an issue but it can be. The only other functionality that $cacheFactory provides is that it allows you to limit the number of entries in a cache.
Beyond that, you do have to worry about application-level coherence issues. Aside from the more typical cache coherence issues where different clients have different views of the model and cause conflicts, I've also seen quite a few bugs where, within a single client, one object is cached thus an older version is used, while the newer version of another object is returned from the service and the combination of the two violates some rule/invariant that the application relies on. For example, one object may contain references that need to be resolved in another, but because you're looking at an old version, that may not be there.