From 6c569e508534a9d77281dd1d724fdb105302b2b3 Mon Sep 17 00:00:00 2001 From: Mantas Masalskis Date: Tue, 5 Nov 2019 18:32:07 +0100 Subject: [PATCH] Maintenance: Replaced not used list method by introducing keys method of App.LocalStorage to support deleting all keys for a certain user only. --- .../app/lib/app_init/local_storage.coffee | 24 ++++++++++--- public/assets/tests/local_storage.js | 35 +++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/app/lib/app_init/local_storage.coffee b/app/assets/javascripts/app/lib/app_init/local_storage.coffee index db2bad695..925b691af 100644 --- a/app/assets/javascripts/app/lib/app_init/local_storage.coffee +++ b/app/assets/javascripts/app/lib/app_init/local_storage.coffee @@ -21,10 +21,10 @@ class App.LocalStorage _instance ?= new _storeSingleton _instance.clear() - @list: -> + @keys: (prefix, user_id) -> if _instance == undefined _instance ?= new _storeSingleton - _instance.list() + _instance.keys(prefix, user_id) @usage: -> if _instance == undefined @@ -63,8 +63,24 @@ class _storeSingleton localStorage.clear() # return list of all keys - list: -> - window.localStorage + keys: (prefix, user_id) -> + allKeys = Object.keys(window.localStorage) + + if user_id is null and prefix is null + return allKeys + + startingWith = '' + + if user_id + startingWith = "personal::#{user_id}::" + + if prefix + startingWith += prefix + + regexp = new RegExp('^' + startingWith) + + allKeys.filter (elem) -> elem.match(regexp) + # get usage usage: -> diff --git a/public/assets/tests/local_storage.js b/public/assets/tests/local_storage.js index 35f94db4b..5e5a87918 100644 --- a/public/assets/tests/local_storage.js +++ b/public/assets/tests/local_storage.js @@ -27,4 +27,39 @@ test('Test user-specific item removal from local storage', function() { equal(App.LocalStorage.get(key, user_id), undefined) }); +test('Test key lookup', function() { + App.LocalStorage.clear() + + var key = 'test_key_3' + var value = 'test_value_3' + var user_id = 2 + var alt_key = 'test_alt_key_3' + + // verify no keys initially + equal(App.LocalStorage.keys().length, 0) + + App.LocalStorage.set(key, value, user_id) + + // has 1 key in total + equal(App.LocalStorage.keys().length, 1) + + // doesn't return anything with wrong prefix + equal(App.LocalStorage.keys('a').length, 0) + + // doesn't return anything since user id not given + equal(App.LocalStorage.keys('test').length, 0) + + // correct + equal(App.LocalStorage.keys('test', user_id).length, 1) + + // verify value + equal(App.LocalStorage.keys('test', user_id)[0].match(key + '$'), key) + + App.LocalStorage.set(alt_key, value) + + // returns 1 key without user id + equal(App.LocalStorage.keys('test').length, 1) + equal(App.LocalStorage.keys('test')[0], alt_key) +}); + }