modifier.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import asyncDB from './async';
  2. const limit = 1024;
  3. function put(name, objects, callback) {
  4. asyncDB.then(db => {
  5. const putTransaction = db.transaction(name, 'readwrite');
  6. const putStore = putTransaction.objectStore(name);
  7. const putIndex = putStore.index('id');
  8. objects.forEach(object => {
  9. function add() {
  10. putStore.add(object);
  11. }
  12. putIndex.getKey(object.id).onsuccess = retrieval => {
  13. if (retrieval.target.result) {
  14. putStore.delete(retrieval.target.result).onsuccess = add;
  15. } else {
  16. add();
  17. }
  18. };
  19. });
  20. putTransaction.oncomplete = () => {
  21. const readTransaction = db.transaction(name, 'readonly');
  22. const readStore = readTransaction.objectStore(name);
  23. readStore.count().onsuccess = count => {
  24. const excess = count.target.result - limit;
  25. if (excess > 0) {
  26. readStore.getAll(null, excess).onsuccess =
  27. retrieval => callback(retrieval.target.result.map(({ id }) => id));
  28. }
  29. };
  30. };
  31. });
  32. }
  33. export function evictAccounts(ids) {
  34. asyncDB.then(db => {
  35. const transaction = db.transaction(['accounts', 'statuses'], 'readwrite');
  36. const accounts = transaction.objectStore('accounts');
  37. const accountsIdIndex = accounts.index('id');
  38. const accountsMovedIndex = accounts.index('moved');
  39. const statuses = transaction.objectStore('statuses');
  40. const statusesIndex = statuses.index('account');
  41. function evict(toEvict) {
  42. toEvict.forEach(id => {
  43. accountsMovedIndex.getAllKeys(id).onsuccess =
  44. ({ target }) => evict(target.result);
  45. statusesIndex.getAll(id).onsuccess =
  46. ({ target }) => evictStatuses(target.result.map(({ id }) => id));
  47. accountsIdIndex.getKey(id).onsuccess =
  48. ({ target }) => target.result && accounts.delete(target.result);
  49. });
  50. }
  51. evict(ids);
  52. });
  53. }
  54. export function evictStatus(id) {
  55. return evictStatuses([id]);
  56. }
  57. export function evictStatuses(ids) {
  58. asyncDB.then(db => {
  59. const store = db.transaction('statuses', 'readwrite').objectStore('statuses');
  60. const idIndex = store.index('id');
  61. const reblogIndex = store.index('reblog');
  62. ids.forEach(id => {
  63. reblogIndex.getAllKeys(id).onsuccess =
  64. ({ target }) => target.result.forEach(reblogKey => store.delete(reblogKey));
  65. idIndex.getKey(id).onsuccess =
  66. ({ target }) => target.result && store.delete(target.result);
  67. });
  68. });
  69. }
  70. export function putAccounts(records) {
  71. put('accounts', records, evictAccounts);
  72. }
  73. export function putStatuses(records) {
  74. put('statuses', records, evictStatuses);
  75. }