Last active
May 24, 2016 13:55
-
-
Save bubbobne/e0dbd30852110aee65eeffa50b3a0941 to your computer and use it in GitHub Desktop.
localForage, separe by filtering an input array and store in localforage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Split an array in several sub-array by id. | |
*/ | |
var separeArrayById = function (data) { | |
var valueById = {}; | |
for (var i = 0; i < data.length; i++) { | |
if (!valueById.hasOwnProperty(data[i].id)) { | |
valueById[data[i].id] = data.filter(function (el) { | |
return el.id === data[i].id; | |
}); | |
} | |
} | |
return valueById; | |
} | |
/* | |
Save the value. | |
*/ | |
var copyDataInTheDB = function (data) { | |
localforage.getItem(RILIEVO_KEY + data[0].id).then(function (value) { | |
if (!value) { | |
value = []; | |
} | |
for (var i = 0; i < data.length; i++) { | |
value.push(data[i]); | |
} | |
localforage.setItem(RILIEVO_KEY + data[0].id, value).then(function () { | |
}).catch(function (err) { | |
console.log("errore nel memorizzare " + data[0].id); | |
}); | |
}).catch(function (err) { | |
console.log(err); | |
}); | |
} | |
$http.get(path, | |
{ | |
headers: {'Content-Type': 'application/json', | |
'Authorization': " Basic " + $base64.encode(user.username + ":" + user.pwd) | |
} | |
}).success(function (data) { | |
var valueById = separeArrayById(data); | |
for (var k in valueById) { | |
if (valueById.hasOwnProperty(k)) { | |
copyDataInTheDB(valueById[k]); | |
} | |
} | |
localStorage[LAST_UPDATE_DATA] = new Date(); | |
deferred.resolve(true); | |
}).error(function (reason) { | |
deferred.reject(reason); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment