Skip to content

Commit

Permalink
update IdentifierCache.js so that cache is persisted to disk only if …
Browse files Browse the repository at this point in the history
…it is modified (homebridge#523)
  • Loading branch information
simont77 authored and KhaosT committed Nov 5, 2017
1 parent cd4c1dc commit efe4c05
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/model/IdentifierCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

var util = require('util');
var storage = require('node-persist');
var crypto = require('crypto');

module.exports = {
IdentifierCache: IdentifierCache
Expand All @@ -21,6 +22,7 @@ function IdentifierCache(username) {
this.username = username;
this._cache = {}; // cache[key:string] = id:number
this._usedCache = null; // for usage tracking and expiring old keys
this._savedCacheHash = ""; // for checking if new cache neeed to be saved
}

IdentifierCache.prototype.startTrackingUsage = function() {
Expand Down Expand Up @@ -105,6 +107,7 @@ IdentifierCache.load = function(username) {
if (saved) {
var info = new IdentifierCache(username);
info._cache = saved.cache;
info._savedCacheHash = crypto.createHash('sha1').update(JSON.stringify(info._cache)).digest('hex'); //calculate hash of the saved hash to decide in future if saving of new cache is neeeded
return info;
}
else {
Expand All @@ -113,14 +116,18 @@ IdentifierCache.load = function(username) {
};

IdentifierCache.prototype.save = function() {
var saved = {
cache: this._cache
};
var newCacheHash = crypto.createHash('sha1').update(JSON.stringify(this._cache)).digest('hex'); //calculate hash of new cache
if (newCacheHash != this._savedCacheHash) { //check if cache need to be saved and proceed accordingly
var saved = {
cache: this._cache
};

var key = IdentifierCache.persistKey(this.username);
var key = IdentifierCache.persistKey(this.username);

storage.setItemSync(key, saved);
storage.persistSync();
storage.setItemSync(key, saved);
storage.persistSync();
this._savedCacheHash = newCacheHash; //update hash of saved cache for future use
}
};

IdentifierCache.prototype.remove = function () {
Expand Down

0 comments on commit efe4c05

Please sign in to comment.