diff --git a/src/helpers/releasesInfo.js b/src/helpers/releasesInfo.js index 52b0057..a2e6a33 100644 --- a/src/helpers/releasesInfo.js +++ b/src/helpers/releasesInfo.js @@ -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( @@ -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); } }); diff --git a/src/hooks/useReleases.js b/src/hooks/useReleases.js index 7ce912b..0e1a134 100644 --- a/src/hooks/useReleases.js +++ b/src/hooks/useReleases.js @@ -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); @@ -14,4 +14,4 @@ const useReleases = (gitHubURL) => { return releases; }; -export default useReleases; \ No newline at end of file +export default useReleases;