优化好友列表,不要每次都请求

This commit is contained in:
JohnathanLin 2023-10-29 11:13:49 +08:00
parent f984ac7436
commit 5aa817175e

View File

@ -1,10 +1,67 @@
<script>
$( document ).ready(function() {
var cacheFriendsData = getItem("windypath-friend");
if (cacheFriendsData !== null) {
console.log("from cache")
showFriends(cacheFriendsData)
} else {
console.log("not cache")
$.get("https://getgithubfriend.azurewebsites.net/api/getGithubFriend", { name: '{{ .Get "githubLoginList" }}' }, function(data) {
showFriends(data)
setItem("windypath-friend", data)
});
}
});
// add an entry
// default expiry is 30 days in milliseconds
function setItem(key, value, maxAge = 30 * 60 * 60 * 1000) {
// store the value as the object
// along with the expiry date
let result = {
data : value
}
if(maxAge){
// set the expiry
// from the current date
result.expireTime = Date.now() + maxAge;
}
// stringify the result
// and the data in original storage
window.localStorage.setItem(key, JSON.stringify(result));
}
function getItem(key) {
// get the parsed value of the given key
let result = JSON.parse(window.localStorage.getItem(key));
// if the key has value
if(result){
// if the entry is expired
// remove the entry and return null
if(result.expireTime <= Date.now()){
window.localStorage.removeItem(key);
return null;
}
// else return the value
return result.data;
}
// if the key does not have value
return null;
}
function showFriends(data) {
var dataObj = JSON.parse(data)
Object.keys(dataObj['data']).forEach(element => {
console.log(element, dataObj['data'][element])
// console.log(element, dataObj['data'][element])
$("div.post-content").append(' \
<div class="friend-link"> \
<a href="' + dataObj['data'][element]['websiteUrl'] +'" target="_blank"> \
@ -19,8 +76,8 @@ $( document ).ready(function() {
</div>'
)
});
});
});
}
</script>