authorBooksStorage.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import localForage from 'localforage';
  2. //import _ from 'lodash';
  3. import * as utils from '../../share/utils';
  4. const maxDataSize = 100*1024*1024;//100 Mb
  5. const abStore = localForage.createInstance({
  6. name: 'authorBooksStorage'
  7. });
  8. class AuthorBooksStorage {
  9. constructor() {
  10. }
  11. async init() {
  12. this.cleanStorage(); //no await
  13. }
  14. async setData(key, data) {
  15. if (typeof data !== 'string')
  16. throw new Error('AuthorBooksStorage: data must be a string');
  17. await abStore.setItem(key, data);
  18. await abStore.setItem(`addTime-${key}`, Date.now());
  19. }
  20. async getData(key) {
  21. const item = await abStore.getItem(key);
  22. //обновим addTime
  23. if (item !== undefined)
  24. abStore.setItem(`addTime-${key}`, Date.now());//no await
  25. return item;
  26. }
  27. async removeData(key) {
  28. await abStore.removeItem(key);
  29. await abStore.removeItem(`addTime-${key}`);
  30. }
  31. async cleanStorage() {
  32. await utils.sleep(5000);
  33. while (1) {// eslint-disable-line no-constant-condition
  34. let size = 0;
  35. let min = Date.now();
  36. let toDel = null;
  37. for (const key of (await abStore.keys())) {
  38. if (key.indexOf('addTime-') == 0)
  39. continue;
  40. const item = await abStore.getItem(key);
  41. const addTime = await abStore.getItem(`addTime-${key}`);
  42. size += item.length;
  43. if (addTime < min) {
  44. toDel = key;
  45. min = addTime;
  46. }
  47. }
  48. if (size > maxDataSize && toDel) {
  49. await this.removeData(toDel);
  50. } else {
  51. break;
  52. }
  53. }
  54. }
  55. }
  56. export default new AuthorBooksStorage();