Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
Fix: Added expiration date on local storage (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
swatikode authored and abhijit945 committed Nov 7, 2019
1 parent dd82b59 commit 2e72dbb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
19 changes: 17 additions & 2 deletions src/helpers/releasesInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import constants from "./constants";
export const retrieveReleases = gitHubURL =>
new Promise((resolve, reject) => {
const repositoryName = gitHubURL.split("github.com")[1];
const lsReleasesData = localStorage.getItem(constants.LOCAL_STORAGE.RELEASES_DATA) || "";
const releasesData = lsReleasesData.split(";")[0];
const lsReleasesTimeStampEntry = lsReleasesData.split(";")[1] || "";

// Only retrieve releases if timeStamp is within 24hrs
// Return from localStorage if retrieving release the same day; else make an API call
if(new Date() < new Date(lsReleasesTimeStampEntry) ) {
resolve(JSON.parse(releasesData));
return;
}

axios
.get(
constants.GITHUB_API_RELEASE_URL.replace(
Expand All @@ -18,18 +29,22 @@ export const retrieveReleases = gitHubURL =>
)
.then(response => {
if (response.status === 200) {
// Set a expiry date as 24hrs from the creation on the local storage item.
const expiryDate = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));
localStorage.setItem(constants.LOCAL_STORAGE.GET_RELEASES_ETAG, response.headers.etag.toString());
localStorage.setItem(constants.LOCAL_STORAGE.RELEASES_DATA, JSON.stringify(response.data));
localStorage.setItem(constants.LOCAL_STORAGE.RELEASES_DATA, `${JSON.stringify(response.data)};${expiryDate}`);
resolve(response.data);
} else {
localStorage.removeItem(constants.LOCAL_STORAGE.RELEASES_DATA);
resolve([]);
}
})
.catch(err => {
if (err.response && err.response.status === 304) {
resolve(JSON.parse(localStorage.getItem(constants.LOCAL_STORAGE.RELEASES_DATA)));
resolve(JSON.parse(releasesData));
}
else {
localStorage.removeItem(constants.LOCAL_STORAGE.RELEASES_DATA);
reject(err);
}
});
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useReleases.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {retrieveReleases} from "../helpers/releasesInfo";
const useReleases = (gitHubURL) => {
const [releases, setReleases] = useState([]);
useEffect(() => {
// Make a request to get releases
// Retrieve releases only if none present in localStorage
if (!releases.length) {
retrieveReleases(gitHubURL).then((response) => {
setReleases(response);
Expand All @@ -14,4 +14,4 @@ const useReleases = (gitHubURL) => {
return releases;
};

export default useReleases;
export default useReleases;

0 comments on commit 2e72dbb

Please sign in to comment.