From 8e51d8731f7dfdc8a943f4ee6ee4f6942ec03844 Mon Sep 17 00:00:00 2001 From: Victor Tortolero Date: Tue, 29 Nov 2022 13:26:32 -0600 Subject: [PATCH] Remove side-effect in StorageAPI that overrides localStorage.clear --- .changeset/gold-cups-scream.md | 5 ++++ .../src/storage/__tests__/base.spec.ts | 6 +++- packages/graphiql-toolkit/src/storage/base.ts | 29 ++++++++++++++----- 3 files changed, 32 insertions(+), 8 deletions(-) create mode 100644 .changeset/gold-cups-scream.md diff --git a/.changeset/gold-cups-scream.md b/.changeset/gold-cups-scream.md new file mode 100644 index 00000000000..8896d3ee023 --- /dev/null +++ b/.changeset/gold-cups-scream.md @@ -0,0 +1,5 @@ +--- +'@graphiql/toolkit': patch +--- + +Remove side-effect in StorageAPI that overrides localStorage.clear diff --git a/packages/graphiql-toolkit/src/storage/__tests__/base.spec.ts b/packages/graphiql-toolkit/src/storage/__tests__/base.spec.ts index 7c849146d73..0d662948cbf 100644 --- a/packages/graphiql-toolkit/src/storage/__tests__/base.spec.ts +++ b/packages/graphiql-toolkit/src/storage/__tests__/base.spec.ts @@ -1,7 +1,11 @@ import { StorageAPI } from '../base'; describe('StorageAPI', () => { - const storage = new StorageAPI(); + let storage = new StorageAPI(); + + beforeEach(() => { + storage = new StorageAPI(); + }); it('returns nothing if no value set', () => { const result = storage.get('key1'); diff --git a/packages/graphiql-toolkit/src/storage/base.ts b/packages/graphiql-toolkit/src/storage/base.ts index 4af7b1447ae..cfc73e0cf67 100644 --- a/packages/graphiql-toolkit/src/storage/base.ts +++ b/packages/graphiql-toolkit/src/storage/base.ts @@ -61,14 +61,29 @@ export class StorageAPI { // Passing `null` creates a noop storage this.storage = null; } else if (typeof window !== 'undefined') { - this.storage = window.localStorage; - // We only want to clear the namespaced items - this.storage.clear = () => { - for (const key in window.localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - window.localStorage.removeItem(key); + this.storage = { + getItem: window.localStorage.getItem.bind(window.localStorage), + setItem: window.localStorage.setItem.bind(window.localStorage), + removeItem: window.localStorage.removeItem.bind(window.localStorage), + + get length() { + let keys = 0; + for (const key in window.localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + keys += 1; + } } - } + return keys; + }, + + clear: () => { + // We only want to clear the namespaced items + for (const key in window.localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + window.localStorage.removeItem(key); + } + } + }, }; } else { this.storage = null;