Browse Source

Improved error handling of temp browser store.

Martin Edenhofer 8 years ago
parent
commit
f170a8a870

+ 15 - 3
app/assets/javascripts/app/lib/app_init/local_storage.coffee

@@ -26,6 +26,11 @@ class App.LocalStorage
       _instance ?= new _storeSingleton
     _instance.list()
 
+  @usage: ->
+    if _instance == undefined
+      _instance ?= new _storeSingleton
+    _instance.usage()
+
 # The actual Singleton class
 class _storeSingleton
   constructor: ->
@@ -37,9 +42,7 @@ class _storeSingleton
         key = "personal::#{user_id}::#{key}"
       localStorage.setItem(key, JSON.stringify(value))
     catch e
-      if e is QUOTA_EXCEEDED_ERR
-        # do something nice to notify your users
-        App.Log.error 'App.LocalStorage', 'Local storage quote exceeded!'
+      App.Log.error 'App.LocalStorage', 'Local storage error!', e
 
   # get item
   get: (key, user_id) ->
@@ -62,3 +65,12 @@ class _storeSingleton
   # return list of all keys
   list: ->
     window.localStorage
+
+  # get usage
+  usage: ->
+    total = ''
+    for key of window.localStorage
+      value = localStorage.getItem(key)
+      if _.isString(value)
+        total += value
+    byteLength(total)

+ 16 - 3
app/assets/javascripts/app/lib/app_init/session_storage.coffee

@@ -26,6 +26,11 @@ class App.SessionStorage
       _instance ?= new _storeSingleton
     _instance.list()
 
+  @usage: ->
+    if _instance == undefined
+      _instance ?= new _storeSingleton
+    _instance.usage()
+
 # The actual Singleton class
 class _storeSingleton
   constructor: ->
@@ -38,9 +43,8 @@ class _storeSingleton
     try
       sessionStorage.setItem(key, JSON.stringify(value))
     catch e
-      if e is QUOTA_EXCEEDED_ERR
-        # do something nice to notify your users
-        App.Log.error 'App.SessionStorage', 'Session storage quote exceeded!'
+      @clear()
+      App.Log.error 'App.SessionStorage', 'Session storage error!', e
 
   # get item
   get: (key) ->
@@ -59,3 +63,12 @@ class _storeSingleton
   # return list of all keys
   list: ->
     window.sessionStorage
+
+  # get usage
+  usage: ->
+    total = ''
+    for key of window.sessionStorage
+      value = sessionStorage.getItem(key)
+      if _.isString(value)
+        total += value
+    byteLength(total)

+ 13 - 0
app/assets/javascripts/application.js

@@ -80,6 +80,19 @@ function difference(object1, object2) {
   return changes;
 }
 
+// returns the byte length of an utf8 string
+// taken from http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
+function byteLength(str) {
+  var s = str.length
+  for (var i=str.length-1; i>=0; i--) {
+    var code = str.charCodeAt(i)
+    if (code > 0x7f && code <= 0x7ff) s++
+    else if (code > 0x7ff && code <= 0xffff) s+=2
+    if (code >= 0xDC00 && code <= 0xDFFF) i-- //trail surrogate
+  }
+  return s
+}
+
 // clone, just data, no instances of objects
 function clone(item, full) {