authorBooksStorage.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. const storageVersion = '1';
  9. class AuthorBooksStorage {
  10. constructor() {
  11. }
  12. async init() {
  13. this.cleanStorage(); //no await
  14. }
  15. async setData(key, data) {
  16. key += storageVersion;
  17. if (typeof data !== 'string')
  18. throw new Error('AuthorBooksStorage: data must be a string');
  19. await abStore.setItem(key, data);
  20. await abStore.setItem(`addTime-${key}`, Date.now());
  21. }
  22. async getData(key) {
  23. key += storageVersion;
  24. const item = await abStore.getItem(key);
  25. //обновим addTime
  26. if (item !== undefined)
  27. abStore.setItem(`addTime-${key}`, Date.now());//no await
  28. return item;
  29. }
  30. async _removeData(fullKey) {
  31. await abStore.removeItem(fullKey);
  32. await abStore.removeItem(`addTime-${fullKey}`);
  33. }
  34. async cleanStorage() {
  35. await utils.sleep(5000);
  36. while (1) {// eslint-disable-line no-constant-condition
  37. let size = 0;
  38. let min = Date.now();
  39. let toDel = null;
  40. for (const key of (await abStore.keys())) {
  41. if (key.indexOf('addTime-') == 0)
  42. continue;
  43. const item = await abStore.getItem(key);
  44. const addTime = await abStore.getItem(`addTime-${key}`);
  45. size += item.length;
  46. if (addTime < min) {
  47. toDel = key;
  48. min = addTime;
  49. }
  50. }
  51. if (size > maxDataSize && toDel) {
  52. await this._removeData(toDel);
  53. } else {
  54. break;
  55. }
  56. }
  57. }
  58. }
  59. export default new AuthorBooksStorage();