All files / src/apps/gbs-music-web/store backupMusicMiddleware.ts

0% Statements 0/17
0% Branches 0/9
0% Functions 0/4
0% Lines 0/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                                                                           
import { Dispatch, isAction, Middleware } from "@reduxjs/toolkit";
import { MusicEditorRootState } from "gbs-music-web/store/configureStore";
import throttle from "lodash/throttle";
import { Song } from "shared/lib/uge/types";
import {
  BACKUP_SONG_KEY,
  BACKUP_TIMESTAMP_KEY,
  serializeSong,
} from "gbs-music-web/lib/songBackup";
 
const throttledWriteToLocalStorage = throttle(
  (song: Song) => {
    localStorage.setItem(BACKUP_SONG_KEY, serializeSong(song));
    localStorage.setItem(BACKUP_TIMESTAMP_KEY, String(Date.now()));
  },
  3000,
  {
    leading: false,
  },
);
 
const backupMusicMiddleware: Middleware<Dispatch, MusicEditorRootState> =
  (store) => (next) => (action) => {
    next(action);
 
    Iif (!isAction(action)) {
      return;
    }
 
    Iif (
      action.type.startsWith("trackerDocument/") &&
      !action.type.startsWith("trackerDocument/loadSong") &&
      !action.type.startsWith("trackerDocument/saveSong") &&
      !action.type.startsWith("trackerDocument/addNewSong") &&
      !action.type.startsWith("trackerDocument/unloadSong") &&
      !action.type.startsWith("trackerDocument/requestAddNewSong")
    ) {
      const state = store.getState();
      Iif (state.trackerDocument.present.song) {
        throttledWriteToLocalStorage(state.trackerDocument.present.song);
      }
    }
  };
 
export default backupMusicMiddleware;