createStorage.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Noop storage for instances where storage is not available
  2. const noopStorage: Storage = {
  3. length: 0,
  4. // Returns null if index does not exist:
  5. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/key
  6. key(_index: number) {
  7. return null;
  8. },
  9. setItem() {
  10. return;
  11. },
  12. clear() {
  13. return undefined;
  14. },
  15. // Returns null if key doesn't exist:
  16. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
  17. getItem() {
  18. return null;
  19. },
  20. removeItem() {
  21. return null;
  22. },
  23. };
  24. // Returns a storage wrapper by trying to perform a single storage op.
  25. // This asserts that storage is both available and that it can be used.
  26. // See https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
  27. const STORAGE_TEST_KEY = 'sentry';
  28. export default function createStorage(getStorage: () => Storage): Storage {
  29. try {
  30. const storage = getStorage();
  31. // Test if a value can be set into the storage.
  32. // This can fail in cases where storage may be full or not available.
  33. storage.setItem(STORAGE_TEST_KEY, STORAGE_TEST_KEY);
  34. storage.removeItem(STORAGE_TEST_KEY);
  35. // If we can set and remove a value, we can use it.
  36. return storage;
  37. } catch (e) {
  38. return noopStorage;
  39. }
  40. }