Skip to content

Commit

Permalink
Addressing Continuous Refreshing in Development Environment (#1466)
Browse files Browse the repository at this point in the history
* Update documentation

* used custom hook for localstorage

* Revert "Update documentation"

This reverts commit 521d8b5.

* fixing documentation conflicts

* removed documentation.zip

* Add pre-commit hook to check localStorage usage

* added check for file in check-localstorage-usage.js script

* Update OrgList.test.tsx

* Update getRefreshToken.test.ts

* updated script and workflow to check for flag

* Update documentation

---------

Co-authored-by: chandel-aman <[email protected]>
  • Loading branch information
chandel-aman and disha1202 authored Feb 10, 2024
1 parent df259fc commit b58ce55
Show file tree
Hide file tree
Showing 194 changed files with 884 additions and 411 deletions.
7 changes: 6 additions & 1 deletion .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ jobs:

- name: Run linting check
if: steps.changed-files.outputs.only_changed != 'true'
run: npm run lint:check
run: npm run lint:check

- name: Check for localStorage Usage
run: |
chmod +x scripts/githooks/check-localstorage-usage.js
node scripts/githooks/check-localstorage-usage.js --scan-entire-repo
- name: Compare translation files
run: |
Expand Down
3 changes: 2 additions & 1 deletion .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"**/*.{ts,tsx,yml}": "eslint --fix",
"**/*.{ts,tsx,json,scss,css,yml}": "prettier --write"
"**/*.{ts,tsx,json,scss,css,yml}": "prettier --write",
"**/*.{ts,tsx}": "node scripts/githooks/check-localstorage-usage.js"
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@
"jest-preview": "jest-preview",
"update:toc": "node scripts/githooks/update-toc.js",
"lint-staged": "lint-staged --concurrent false",
"setup": "tsx setup.ts"
"setup": "tsx setup.ts",
"check-localstorage": "node scripts/githooks/check-localstorage-usage.js"
},
"eslintConfig": {
"extends": [
Expand Down
96 changes: 96 additions & 0 deletions scripts/githooks/check-localstorage-usage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#!/usr/bin/env node

import { readFileSync, existsSync } from 'fs';
import path from 'path';
import { execSync } from 'child_process';

const args = process.argv.slice(2);
const scanEntireRepo = args.includes('--scan-entire-repo');

const containsSkipComment = (file) => {
try {
const content = readFileSync(file, 'utf-8');
return content.includes('// SKIP_LOCALSTORAGE_CHECK');
} catch (error) {
console.error(`Error reading file ${file}:`, error.message);
return false;
}
};

const getModifiedFiles = () => {
try {
if (scanEntireRepo) {
const result = execSync('git ls-files | grep ".tsx\\?$"', {
encoding: 'utf-8',
});
return result.trim().split('\n');
}

const result = execSync('git diff --cached --name-only', {
encoding: 'utf-8',
});
return result.trim().split('\n');
} catch (error) {
console.error('Error fetching modified files:', error.message);
process.exit(1);
}
};

const files = getModifiedFiles();

const filesWithLocalStorage = [];

const checkLocalStorageUsage = (file) => {
if (!file) {
return;
}

const fileName = path.basename(file);

// Skip files with specific names or containing a skip comment
if (
fileName === 'check-localstorage-usage.js' ||
fileName === 'useLocalstorage.test.ts' ||
fileName === 'useLocalstorage.ts' ||
containsSkipComment(file)
) {
console.log(`Skipping file: ${file}`);
return;
}

try {
if (existsSync(file)) {
const content = readFileSync(file, 'utf-8');

if (
content.includes('localStorage.getItem') ||
content.includes('localStorage.setItem') ||
content.includes('localStorage.removeItem')
) {
filesWithLocalStorage.push(file);
}
} else {
console.log(`File ${file} does not exist.`);
}
} catch (error) {
console.error(`Error reading file ${file}:`, error.message);
}
};

files.forEach(checkLocalStorageUsage);

if (filesWithLocalStorage.length > 0) {
console.error('\x1b[31m%s\x1b[0m', '\nError: Found usage of localStorage');
console.error('\nFiles with localStorage usage:');
filesWithLocalStorage.forEach((file) => console.error(file));

console.info(
'\x1b[34m%s\x1b[0m',
'\nInfo: Consider using custom hook functions.'
);
console.info(
'Please use the getItem, setItem, and removeItem functions provided by the custom hook useLocalStorage.\n'
);

process.exit(1);
}
24 changes: 12 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ import Donate from 'screens/UserPortal/Donate/Donate';
import Events from 'screens/UserPortal/Events/Events';
// import Chat from 'screens/UserPortal/Chat/Chat';
import Advertisements from 'components/Advertisements/Advertisements';
import useLocalStorage from 'utils/useLocalstorage';

const { setItem } = useLocalStorage();

function app(): JSX.Element {
/*const { updatePluginLinks, updateInstalled } = bindActionCreators(
Expand Down Expand Up @@ -63,18 +66,15 @@ function app(): JSX.Element {

useEffect(() => {
if (data) {
localStorage.setItem(
'name',
`${data.checkAuth.firstName} ${data.checkAuth.lastName}`
);
localStorage.setItem('id', data.checkAuth._id);
localStorage.setItem('email', data.checkAuth.email);
localStorage.setItem('IsLoggedIn', 'TRUE');
localStorage.setItem('UserType', data.checkAuth.userType);
localStorage.setItem('FirstName', data.checkAuth.firstName);
localStorage.setItem('LastName', data.checkAuth.lastName);
localStorage.setItem('UserImage', data.checkAuth.image);
localStorage.setItem('Email', data.checkAuth.email);
setItem('name', `${data.checkAuth.firstName} ${data.checkAuth.lastName}`);
setItem('id', data.checkAuth._id);
setItem('email', data.checkAuth.email);
setItem('IsLoggedIn', 'TRUE');
setItem('UserType', data.checkAuth.userType);
setItem('FirstName', data.checkAuth.firstName);
setItem('LastName', data.checkAuth.lastName);
setItem('UserImage', data.checkAuth.image);
setItem('Email', data.checkAuth.email);
}
}, [data, loading]);

Expand Down
5 changes: 4 additions & 1 deletion src/components/AddOn/core/AddOnEntry/AddOnEntry.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ import { MockedProvider, wait } from '@apollo/react-testing';
import { StaticMockLink } from 'utils/StaticMockLink';
import { ADD_ON_ENTRY_MOCK } from './AddOnEntryMocks';
import { ToastContainer } from 'react-toastify';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

const link = new StaticMockLink(ADD_ON_ENTRY_MOCK, true);

const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});
console.error = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@ import { BACKEND_URL } from 'Constant/constant';
import i18nForTest from 'utils/i18nForTest';
import { I18nextProvider } from 'react-i18next';
import { toast } from 'react-toastify';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});

Expand Down
5 changes: 4 additions & 1 deletion src/components/AddOn/core/AddOnStore/AddOnStore.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@ import { store } from 'state/store';
import { BACKEND_URL } from 'Constant/constant';
import i18nForTest from 'utils/i18nForTest';
import { I18nextProvider } from 'react-i18next';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});

Expand Down
5 changes: 4 additions & 1 deletion src/components/Advertisements/Advertisements.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ import {
import userEvent from '@testing-library/user-event';
import { ADD_ADVERTISEMENT_MUTATION } from 'GraphQl/Mutations/mutations';
import { ToastContainer } from 'react-toastify';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ import { BACKEND_URL } from 'Constant/constant';
import i18nForTest from 'utils/i18nForTest';
import { I18nextProvider } from 'react-i18next';
import dayjs from 'dayjs';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});
const translations = JSON.parse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import { toast } from 'react-toastify';
import { ADD_ADVERTISEMENT_MUTATION } from 'GraphQl/Mutations/mutations';
import dayjs from 'dayjs';
import { StaticMockLink } from 'utils/StaticMockLink';
import useLocalStorage from 'utils/useLocalstorage';

const { getItem } = useLocalStorage();

jest.mock('react-toastify', () => ({
toast: {
Expand Down Expand Up @@ -60,7 +63,7 @@ const link = new StaticMockLink(MOCKS, true);
const httpLink = new HttpLink({
uri: BACKEND_URL,
headers: {
authorization: 'Bearer ' + localStorage.getItem('token') || '',
authorization: 'Bearer ' + getItem('token') || '',
},
});

Expand Down
15 changes: 9 additions & 6 deletions src/components/DeleteOrg/DeleteOrg.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import i18nForTest from 'utils/i18nForTest';
import DeleteOrg from './DeleteOrg';
import { ToastContainer, toast } from 'react-toastify';
import { IS_SAMPLE_ORGANIZATION_QUERY } from 'GraphQl/Queries/Queries';
import useLocalStorage from 'utils/useLocalstorage';

const { setItem } = useLocalStorage();

async function wait(ms = 1000): Promise<void> {
await act(async () => {
Expand Down Expand Up @@ -106,7 +109,7 @@ afterEach(() => {
describe('Delete Organization Component', () => {
test('should be able to Toggle Delete Organization Modal', async () => {
window.location.assign('/orgsetting/id=456');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
Expand All @@ -131,7 +134,7 @@ describe('Delete Organization Component', () => {

test('should be able to Toggle Delete Organization Modal When Organization is Sample Organization', async () => {
window.location.assign('/orgsetting/id=123');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
Expand All @@ -156,7 +159,7 @@ describe('Delete Organization Component', () => {

test('Delete organization functionality should work properly', async () => {
window.location.assign('/orgsetting/id=456');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
Expand All @@ -177,7 +180,7 @@ describe('Delete Organization Component', () => {

test('Delete organization functionality should work properly for sample org', async () => {
window.location.assign('/orgsetting/id=123');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
Expand All @@ -198,7 +201,7 @@ describe('Delete Organization Component', () => {

test('Error handling for IS_SAMPLE_ORGANIZATION_QUERY mock', async () => {
window.location.assign('/orgsetting/id=123');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
jest.spyOn(toast, 'error');
render(
<MockedProvider addTypename={false} link={link2}>
Expand All @@ -222,7 +225,7 @@ describe('Delete Organization Component', () => {

test('Error handling for DELETE_ORGANIZATION_MUTATION mock', async () => {
window.location.assign('/orgsetting/id=456');
localStorage.setItem('UserType', 'SUPERADMIN');
setItem('UserType', 'SUPERADMIN');
render(
<MockedProvider addTypename={false} link={link2}>
<BrowserRouter>
Expand Down
4 changes: 3 additions & 1 deletion src/components/DeleteOrg/DeleteOrg.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import {
} from 'GraphQl/Mutations/mutations';
import { IS_SAMPLE_ORGANIZATION_QUERY } from 'GraphQl/Queries/Queries';
import styles from './DeleteOrg.module.css';
import useLocalStorage from 'utils/useLocalstorage';

function deleteOrg(): JSX.Element {
const { t } = useTranslation('translation', {
keyPrefix: 'deleteOrg',
});
const [showDeleteModal, setShowDeleteModal] = useState(false);
const { getItem } = useLocalStorage();
const currentUrl = window.location.href.split('=')[1];
const canDelete = localStorage.getItem('UserType') === 'SUPERADMIN';
const canDelete = getItem('UserType') === 'SUPERADMIN';
const toggleDeleteModal = (): void => setShowDeleteModal(!showDeleteModal);

const [del] = useMutation(DELETE_ORGANIZATION_MUTATION);
Expand Down
Loading

0 comments on commit b58ce55

Please sign in to comment.