All files / src/store/features/assets assetsMiddleware.ts

100% Statements 19/19
87.5% Branches 14/16
100% Functions 4/4
100% Lines 17/17

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63  1x   1x       1x     3x 3x 3x 3x       3x       3x   3x   3x   3x 3x             2x               2x                             3x     1x  
import { Middleware, Dispatch } from "@reduxjs/toolkit";
import actions from "./assetsActions";
import { RootState } from "store/configureStore";
import {
  backgroundSelectors,
  tilesetSelectors,
} from "store/features/entities/entitiesState";
import API from "renderer/lib/api";
 
const assetsMiddleware: Middleware<Dispatch, RootState> =
  (store) => (next) => (action) => {
    if (actions.loadBackgroundAssetInfo.match(action)) {
      const state = store.getState();
      const background = backgroundSelectors.selectById(
        state,
        action.payload.backgroundId
      );
      const tileset = tilesetSelectors.selectById(
        state,
        action.payload.tilesetId ?? ""
      );
      const tilesetId = tileset?.id;
 
      const isCGBOnly = state.project.present.settings.colorMode === "color";
 
      if (background) {
        const cachedWarnings =
          state.assets.backgrounds[action.payload.backgroundId];
        if (
          !cachedWarnings ||
          cachedWarnings.timestamp < background._v ||
          cachedWarnings.is360 !== action.payload.is360 ||
          cachedWarnings.isCGBOnly !== isCGBOnly ||
          cachedWarnings.tilesetId !== tilesetId
        ) {
          API.project
            .getBackgroundInfo(
              background,
              tileset,
              action.payload.is360,
              isCGBOnly
            )
            .then((info) => {
              store.dispatch(
                actions.setBackgroundAssetInfo({
                  id: action.payload.backgroundId,
                  is360: action.payload.is360,
                  tilesetId,
                  warnings: info.warnings,
                  numTiles: info.numTiles,
                  lookup: info.lookup,
                  isCGBOnly,
                })
              );
            });
        }
      }
    }
    return next(action);
  };
 
export default assetsMiddleware;