All files / src/app/extensions/rating/store/product-reviews product-reviews.reducer.ts

66.66% Statements 10/15
100% Branches 0/0
50% Functions 3/6
66.66% Lines 10/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 47 48 49 50 51 52 53 54 55 56 57 58 593x 3x     3x       3x                         3x 6x               3x         3x         1x 3x                                  
import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
 
import { HttpError } from 'ish-core/models/http-error/http-error.model';
import { setErrorOn, setLoadingOn, unsetLoadingAndErrorOn } from 'ish-core/utils/ngrx-creators';
 
import { ProductReviews as ProductReviewsModel } from '../../models/product-reviews/product-reviews.model';
 
import {
  createProductReview,
  createProductReviewFail,
  createProductReviewSuccess,
  deleteProductReview,
  deleteProductReviewFail,
  deleteProductReviewSuccess,
  loadProductReviews,
  loadProductReviewsFail,
  loadProductReviewsSuccess,
  resetProductReviewError,
} from './product-reviews.actions';
 
export const productReviewsAdapter = createEntityAdapter<ProductReviewsModel>({
  selectId: review => review.sku,
});
 
export interface ProductReviewsState extends EntityState<ProductReviewsModel> {
  loading: boolean;
  error: HttpError;
}
 
const initialState: ProductReviewsState = productReviewsAdapter.getInitialState({
  loading: false,
  error: undefined,
});
 
export const productReviewsReducer = createReducer(
  initialState,
  setLoadingOn(loadProductReviews, createProductReview, deleteProductReview),
  unsetLoadingAndErrorOn(loadProductReviewsSuccess, createProductReviewSuccess, deleteProductReviewSuccess),
  setErrorOn(loadProductReviewsFail, createProductReviewFail, deleteProductReviewFail),
  on(resetProductReviewError, loadProductReviews, (state): ProductReviewsState => ({ ...state, error: undefined })),
  on(loadProductReviewsSuccess, (state, action) => productReviewsAdapter.upsertOne(action.payload.reviews, state)),
  on(createProductReviewSuccess, (state, action) => {
    const productReviews: ProductReviewsModel = {
      sku: action.payload.reviews.sku,
      reviews: state.entities[action.payload.reviews.sku]?.reviews?.concat(action.payload.reviews.reviews),
    };
 
    return productReviewsAdapter.upsertOne(productReviews, state);
  }),
  on(deleteProductReviewSuccess, (state, action) => {
    const productReviews: ProductReviewsModel = {
      sku: action.payload.sku,
      reviews: state.entities[action.payload.sku]?.reviews?.filter(review => review.id !== action.payload.review.id),
    };
    return productReviewsAdapter.upsertOne(productReviews, state);
  })
);