Skip to content

Commit

Permalink
feat: add localstorage cacheing
Browse files Browse the repository at this point in the history
  • Loading branch information
limsohee1002 committed Nov 6, 2024
1 parent 8c0497b commit 76b47ba
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 18 deletions.
37 changes: 23 additions & 14 deletions assets/shared-bundle.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions assets/tailwind-output.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions src/modules/side-nav/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SideNavData } from '../../lib/types';
import { SideNavDataManager } from '../../utils/localStorage';

const makeArrayToHaveUniqueValues = (array: { id: number }[]) => {
return array.filter((value, index, self) => self.findIndex((v) => v.id === value.id) === index);
Expand Down Expand Up @@ -77,6 +78,15 @@ const sanitizeResponse = (response: SideNavApiResponse): SideNavData => {

export const sideNav = {
get: async (): Promise<SideNavData> => {
const storedSideNavData = SideNavDataManager.get();
const expriresAt = storedSideNavData?.expriresAt;

if (expriresAt && expriresAt > Date.now() && storedSideNavData.data) {
return storedSideNavData.data;
} else {
SideNavDataManager.clear();
}

const url = `${window.location.origin}/api/v2/help_center/en-us/articles.json?include=categories,sections&per_page=100`;

try {
Expand Down Expand Up @@ -121,6 +131,14 @@ export const sideNav = {
};
const sanitizedResponse = sanitizeResponse(allPagesResponseData);

// we cache the response for 24 hours
const millisecondsIn24Hours = 24 * 60 * 60 * 1000;

SideNavDataManager.set({
expriresAt: Date.now() + millisecondsIn24Hours,
data: sanitizedResponse,
});

return sanitizedResponse;
} catch (error) {
console.error(error);
Expand Down
31 changes: 31 additions & 0 deletions src/utils/localStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { SideNavData } from '../lib/types';

export class LocalStorageManager<T> {
key: string;

constructor(key: string) {
this.key = key;
}

set(value: T): void {
const valueToSet = typeof value === 'string' ? value : JSON.stringify(value);
localStorage.setItem(this.key, valueToSet);
}

get(): T | undefined {
const value = localStorage.getItem(this.key);
if (value) {
return JSON.parse(value);
}
return undefined;
}

clear(): void {
localStorage.removeItem(this.key);
}
}

export const SideNavDataManager = new LocalStorageManager<{
expriresAt: number;
data: SideNavData;
}>('SIDE_NAV_DATA');

0 comments on commit 76b47ba

Please sign in to comment.