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

98.24% Statements 56/57
75.67% Branches 28/37
100% Functions 22/22
98.24% Lines 56/57

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 157 158 159 160 161 162 16317x 17x 17x 17x 17x 17x 17x 17x                     17x 17x 17x 17x 17x 17x 17x 17x         17x 17x 17x               17x     17x   55x 55x 55x 55x 55x 55x 55x 55x           55x 55x                     9x   9x       55x 55x     11x 11x 11x   11x     11x       11x 28x     28x                                       55x     55x             8x 7x 1x           55x   55x   1x         55x 55x     70x         14x     14x                
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 { TranslateService } from '@ngx-translate/core';
import { EMPTY, from } from 'rxjs';
import {
  catchError,
  concatMap,
  debounceTime,
  distinctUntilChanged,
  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 { ProductsService } from 'ish-core/services/products/products.service';
import { SuggestService } from 'ish-core/services/suggest/suggest.service';
import { ofUrl, selectRouteParam } from 'ish-core/store/core/router';
import { setBreadcrumbData } from 'ish-core/store/core/viewconf';
import { personalizationStatusDetermined } from 'ish-core/store/customer/user';
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 { searchProducts, searchProductsFail, suggestSearch, suggestSearchSuccess } from './search.actions';
 
@Injectable()
export class SearchEffects {
  constructor(
    private actions$: Actions,
    private store: Store,
    private productsService: ProductsService,
    private suggestService: SuggestService,
    private httpStatusCodeService: HttpStatusCodeService,
    private productListingMapper: ProductListingMapper,
    private translateService: TranslateService,
    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(),
      map(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, sorting, offset, page }) =>
        this.productsService.searchProducts(searchTerm, amount, sorting, offset).pipe(
          concatMap(({ total, products, sortableAttributes }) => {
            // 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,
                  }
                )
              ),
            ];
          }),
          mapErrorToAction(searchProductsFail)
        )
      )
    )
  );
 
  suggestSearch$ =
    !SSR &&
    createEffect(() =>
      this.actions$.pipe(
        ofType(suggestSearch),
        mapToPayloadProperty('searchTerm'),
        debounceTime(400),
        distinctUntilChanged(),
        whenTruthy(),
        switchMap(searchTerm =>
          this.suggestService.search(searchTerm).pipe(
            map(suggests => suggestSearchSuccess({ searchTerm, suggests })),
            catchError(() => EMPTY)
          )
        )
      )
    );
 
  redirectIfSearchProductFail$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(searchProductsFail),
        concatMap(() => from(this.httpStatusCodeService.setStatus(404)))
      ),
    { dispatch: false }
  );
 
  setSearchBreadcrumb$ = createEffect(() =>
    this.actions$.pipe(
      ofType(routerNavigatedAction),
      switchMap(() =>
        this.store.pipe(
          ofUrl(/^\/search.*/),
          select(selectRouteParam('searchTerm')),
          whenTruthy(),
          switchMap(searchTerm =>
            this.translateService
              .get('search.breadcrumbs.your_search.label')
              .pipe(
                map(translation => setBreadcrumbData({ breadcrumbData: [{ text: `${translation} ${searchTerm}` }] }))
              )
          )
        )
      )
    )
  );
}