mutationCache.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { notifyManager } from './notifyManager.mjs';
  2. import { Mutation } from './mutation.mjs';
  3. import { matchMutation, noop } from './utils.mjs';
  4. import { Subscribable } from './subscribable.mjs';
  5. // CLASS
  6. class MutationCache extends Subscribable {
  7. constructor(config) {
  8. super();
  9. this.config = config || {};
  10. this.mutations = [];
  11. this.mutationId = 0;
  12. }
  13. build(client, options, state) {
  14. const mutation = new Mutation({
  15. mutationCache: this,
  16. logger: client.getLogger(),
  17. mutationId: ++this.mutationId,
  18. options: client.defaultMutationOptions(options),
  19. state,
  20. defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined
  21. });
  22. this.add(mutation);
  23. return mutation;
  24. }
  25. add(mutation) {
  26. this.mutations.push(mutation);
  27. this.notify({
  28. type: 'added',
  29. mutation
  30. });
  31. }
  32. remove(mutation) {
  33. this.mutations = this.mutations.filter(x => x !== mutation);
  34. this.notify({
  35. type: 'removed',
  36. mutation
  37. });
  38. }
  39. clear() {
  40. notifyManager.batch(() => {
  41. this.mutations.forEach(mutation => {
  42. this.remove(mutation);
  43. });
  44. });
  45. }
  46. getAll() {
  47. return this.mutations;
  48. }
  49. find(filters) {
  50. if (typeof filters.exact === 'undefined') {
  51. filters.exact = true;
  52. }
  53. return this.mutations.find(mutation => matchMutation(filters, mutation));
  54. }
  55. findAll(filters) {
  56. return this.mutations.filter(mutation => matchMutation(filters, mutation));
  57. }
  58. notify(event) {
  59. notifyManager.batch(() => {
  60. this.listeners.forEach(({
  61. listener
  62. }) => {
  63. listener(event);
  64. });
  65. });
  66. }
  67. resumePausedMutations() {
  68. var _this$resuming;
  69. this.resuming = ((_this$resuming = this.resuming) != null ? _this$resuming : Promise.resolve()).then(() => {
  70. const pausedMutations = this.mutations.filter(x => x.state.isPaused);
  71. return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop)), Promise.resolve()));
  72. }).then(() => {
  73. this.resuming = undefined;
  74. });
  75. return this.resuming;
  76. }
  77. }
  78. export { MutationCache };
  79. //# sourceMappingURL=mutationCache.mjs.map