'use strict';
// --- Parameters --- //
var
navHooker =
jQuery(
'#myNavigation > ul');
// --- Check if we will use Local Storage or Live data --- //
if (
localStorage.
getItem(
'myLsItem') ===
null) {
getFromAPI();
}
else {
var
minutes =
1000 *
60;
var
hours =
minutes *
60;
var
now =
new
Date().
getTime().
toString();
var
data =
JSON.
parse(
localStorage.
getItem(
'myLsItem'));
if(
now > (
data[
'myTime'] + (
1 *
hours))){
getFromAPI();
}
else {
getFromLS(
data);
}
}
// Get data from Local Storage
function
getFromLS(){
var
myItem =
data.
items[
0].
volumeInfo.
title;
jQuery(
navHooker).
append(
myItem);
console.
log(
'fetch from Local Storge..' +
myItem);
}
// Get data from API
function
getFromAPI(){
jQuery.
ajax({
url:
url,
dataType:
'jsonp',
success :
function(
data) {
var
myItem =
data.
items[
0].
volumeInfo.
title;
jQuery(
navHooker).
append(
myItem);
// var time now, append it to the end of the data object and stringify so it can be stored in Local Storage
var
appTime =
new
Date().
getTime();
data.
myTime =
appTime;
var
jsonStore =
JSON.
stringify(
data);
localStorage.
setItem(
'myLsItem',
jsonStore);
console.
log(
'fetch from API..' +
myItem );
}
});
}