Skip to content

Commit

Permalink
Merge pull request #1668 from OskarDamkjaer/throttle_localstore_writes
Browse files Browse the repository at this point in the history
Debounce writing to localstorage to improve performance
  • Loading branch information
OskarDamkjaer committed Feb 10, 2022
2 parents 849d092 + fe65ada commit 3f1ee1e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 25 deletions.
2 changes: 2 additions & 0 deletions src/shared/services/localstorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
import * as ls from './localstorage'

jest.mock('lodash-es/debounce', () => (fn: any) => fn)

describe('localstorage', () => {
test('getItem return items', () => {
// Given
Expand Down
60 changes: 35 additions & 25 deletions src/shared/services/localstorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { debounce } from 'lodash-es'
import { Middleware } from 'redux'

import {
Expand Down Expand Up @@ -83,36 +84,45 @@ export function getAll(): Partial<GlobalState> {
return out
}

function storeReduxInLocalStorage(state: GlobalState) {
keys.forEach(key => {
if (key === 'connections' && !shouldRetainConnectionCredentials(state)) {
// if browser.retain_connection_credentials is not true, overwrite password value on all connections
setItem(key, {
...state[key],
connectionsById: Object.assign(
{},
...Object.entries(state[key].connectionsById).map(
([id, connection]) => ({
[id]: {
...(connection as Record<string, unknown>),
password: ''
}
})
)
)
})
} else if (key === 'history' && !shouldRetainEditorHistory(state)) {
setItem(key, [])
} else if (key === 'guides') {
setItem(key, { ...state[key], currentGuide: null })
} else {
setItem(key, state[key])
}
})
}

const debouncedStore = debounce(storeReduxInLocalStorage, 500, {
trailing: true,
maxWait: 1000
})

export function createReduxMiddleware(): Middleware {
return store => next => action => {
const result = next(action)
const state = store.getState() as unknown as GlobalState
debouncedStore(state)

keys.forEach(key => {
if (key === 'connections' && !shouldRetainConnectionCredentials(state)) {
// if browser.retain_connection_credentials is not true, overwrite password value on all connections
setItem(key, {
...state[key],
connectionsById: Object.assign(
{},
...Object.entries(state[key].connectionsById).map(
([id, connection]) => ({
[id]: {
...(connection as Record<string, unknown>),
password: ''
}
})
)
)
})
} else if (key === 'history' && !shouldRetainEditorHistory(state)) {
setItem(key, [])
} else if (key === 'guides') {
setItem(key, { ...state[key], currentGuide: null })
} else {
setItem(key, state[key])
}
})
return result
}
}
Expand Down

0 comments on commit 3f1ee1e

Please sign in to comment.