All files / src/app/core/store/shopping/search search.effects.ts

92.85% Statements 52/56
70.27% Branches 26/37
94.44% Functions 17/18
94.54% Lines 52/55

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 15719x 19x 19x 19x 19x   19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x         19x 19x 19x               19x                   19x   51x 51x 51x 51x 51x 51x 51x           51x 51x                     9x   9x             51x 51x     11x 11x 11x   11x           11x       11x 14x     14x                                         51x     51x       6x         5x 5x     5x     5x               51x   51x   1x          
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, concatLatestFrom, createEffect, ofType } from '@ngrx/effects';
import { routerNavigatedAction } from '@ngrx/router-store';
import { Store, select } from '@ngrx/store';
import { Action } from '@ngrx/store/src/models';
import { from } from 'rxjs';
import { concatMap, map, sample, switchMap, withLatestFrom } from 'rxjs/operators';
 
import { ProductListingMapper } from 'ish-core/models/product-listing/product-listing.mapper';
import { generateProductUrl } from 'ish-core/routing/product/product.route';
import { ProductsServiceProvider } from 'ish-core/service-provider/products.service-provider';
import { SuggestionsServiceProvider } from 'ish-core/service-provider/suggestions.service-provider';
import { ofUrl, selectRouteParam } from 'ish-core/store/core/router';
import { personalizationStatusDetermined } from 'ish-core/store/customer/user';
import { loadCategorySuccess } from 'ish-core/store/shopping/categories';
import { loadFilterSuccess } from 'ish-core/store/shopping/filter';
import {
  getProductListingItemsPerPage,
  loadMoreProducts,
  setProductListingPages,
} from 'ish-core/store/shopping/product-listing';
import { loadProductSuccess } from 'ish-core/store/shopping/products';
import { HttpStatusCodeService } from 'ish-core/utils/http-status-code/http-status-code.service';
import {
  mapErrorToAction,
  mapToPayload,
  mapToPayloadProperty,
  useCombinedObservableOnAction,
  whenTruthy,
} from 'ish-core/utils/operators';
 
import {
  addSearchTermToSuggestion,
  searchProducts,
  searchProductsFail,
  suggestSearch,
  suggestSearchFail,
  suggestSearchSuccess,
} from './search.actions';
 
@Injectable()
export class SearchEffects {
  constructor(
    private actions$: Actions,
    private store: Store,
    private suggestionsServiceProvider: SuggestionsServiceProvider,
    private productsServiceProvider: ProductsServiceProvider,
    private httpStatusCodeService: HttpStatusCodeService,
    private productListingMapper: ProductListingMapper,
    private router: Router
  ) {}
 
  /**
   * Effect that listens for search route changes and triggers a search action.
   */
  triggerSearch$ = createEffect(() =>
    this.store.pipe(
      sample(
        this.actions$.pipe(
          useCombinedObservableOnAction(
            this.actions$.pipe(ofType(routerNavigatedAction)),
            personalizationStatusDetermined
          )
        )
      ),
      ofUrl(/^\/search.*/),
      withLatestFrom(this.store.pipe(select(selectRouteParam('searchTerm')))),
      map(([, searchTerm]) => searchTerm),
      whenTruthy(),
      concatMap(searchTerm => [
        addSearchTermToSuggestion({ searchTerm }),
        loadMoreProducts({ id: { type: 'search', value: searchTerm } }),
      ])
    )
  );
 
  searchProducts$ = createEffect(() =>
    this.actions$.pipe(
      ofType(searchProducts),
      mapToPayload(),
      map(payload => ({ ...payload, page: payload.page ? payload.page : 1 })),
      concatLatestFrom(() => this.store.pipe(select(getProductListingItemsPerPage('search')))),
      map(([payload, pageSize]) => ({ ...payload, amount: pageSize, offset: (payload.page - 1) * pageSize })),
      concatMap(({ searchTerm, amount, offset, sorting, page }) =>
        this.productsServiceProvider
          .get()
          .searchProducts({ searchTerm, amount, offset, sorting })
          .pipe(
            concatMap(({ total, products, sortableAttributes, filter }) => {
              // route to product detail page if only one product was found
              Iif (total === 1) {
                this.router.navigate([generateProductUrl(products[0])]);
              }
              // provide the data for the search result page
              return [
                ...products.map(product => loadProductSuccess({ product })),
                setProductListingPages(
                  this.productListingMapper.createPages(
                    products.map(p => p.sku),
                    'search',
                    searchTerm,
                    amount,
                    {
                      startPage: page,
                      sorting,
                      sortableAttributes,
                      itemCount: total,
                    }
                  )
                ),
                filter?.length ? loadFilterSuccess({ filterNavigation: { filter } }) : { type: 'no_filter_action' },
              ];
            }),
            mapErrorToAction(searchProductsFail)
          )
      )
    )
  );
 
  suggestSearch$ =
    !SSR &&
    createEffect(() =>
      this.actions$.pipe(
        ofType(suggestSearch),
        mapToPayloadProperty('searchTerm'),
        switchMap(searchTerm =>
          this.suggestionsServiceProvider
            .get()
            .searchSuggestions(searchTerm)
            .pipe(
              concatMap(({ suggestions, categories, products }) => {
                const actions: Action[] = [suggestSearchSuccess({ suggestions })];
                Iif (categories) {
                  actions.push(loadCategorySuccess({ categories }));
                }
                Iif (products) {
                  products.map(product => actions.push(loadProductSuccess({ product })));
                }
                return actions;
              }),
              mapErrorToAction(suggestSearchFail)
            )
        )
      )
    );
 
  redirectIfSearchProductFail$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(searchProductsFail),
        concatMap(() => from(this.httpStatusCodeService.setStatus(404)))
      ),
    { dispatch: false }
  );
}