All files / src/app/core/services/api api.service.ts

74.75% Statements 77/103
72.72% Branches 56/77
67.12% Functions 49/73
76.59% Lines 72/94

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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440153x 153x 153x 153x                         153x   153x     153x           153x 153x 153x 153x 153x                 153x 40x                                                   153x 153x 153x     42x 42x 42x                 2x   2x                         46x   46x     8x                         47x 5x 5x 1x 1x 4x 3x 3x     1x         47x       47x 9x   38x                 38x           38x         38x         32x     32x               38x         32x     32x                     47x     46x 46x                           41x     40x                 2x     2x                 1x     1x                 1x     1x                 1x     1x                 1x     1x                     3x 3x     3x   3x       1x                       5x 5x   6x     5x   5x                         6x                                                                                                                                                                                                                              
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import {
  EMPTY,
  MonoTypeOperatorFunction,
  Observable,
  OperatorFunction,
  combineLatest,
  defer,
  forkJoin,
  identity,
  iif,
  of,
  throwError,
} from 'rxjs';
import { catchError, concatMap, filter, first, map, switchMap, take, withLatestFrom } from 'rxjs/operators';
 
import { FeatureToggleService } from 'ish-core/feature-toggle.module';
import { Captcha } from 'ish-core/models/captcha/captcha.model';
import { Link } from 'ish-core/models/link/link.model';
import {
  getCurrentCurrency,
  getCurrentLocale,
  getICMServerURL,
  getRestEndpoint,
} from 'ish-core/store/core/configuration';
import { communicationTimeoutError, serverError } from 'ish-core/store/core/error';
import { isServerConfigurationLoaded } from 'ish-core/store/core/server-config';
import { getBasketIdOrCurrent } from 'ish-core/store/customer/basket';
import { getLoggedInCustomer, getLoggedInUser, getPGID } from 'ish-core/store/customer/user';
import { whenTruthy } from 'ish-core/utils/operators';
 
/**
 * Pipeable operator for elements translation (removing the envelope).
 *
 * @param key the name of the envelope (default 'elements')
 * @returns The items of an elements array without the elements wrapper.
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any, -- any to avoid having to type everything before
export function unpackEnvelope<T>(key: string = 'elements'): OperatorFunction<any, T[]> {
  return map(data => (data?.[key]?.length ? data[key] : []));
}
 
export interface AvailableOptions {
  params?: HttpParams;
  headers?: HttpHeaders;
  responseType?: string;
  skipApiErrorHandling?: boolean;
  captcha?: Captcha;
  /** opt-out of sending currency matrix parameter by setting it to false */
  sendCurrency?: boolean;
  /** opt-out of sending locale matrix parameter by setting it to false */
  sendLocale?: boolean;
  /**
   * opt-in to sending pgid matrix parameter by setting it to true. As per Intershop Commerce REST api documentation ´pgid´ is the standard means
   * to get and cache personalized content of supported REST resources (e.g. cms).
   */
  sendPGID?: boolean;
  /**
   * opt-in to sending spgid matrix parameter by setting it to true. As per Intershop Commerce REST api documentation this is the special means
   * to get and cache personalized content of the product and category API (1.x).
   */
  sendSPGID?: boolean;
}
 
@Injectable({ providedIn: 'root' })
export class ApiService {
  static TOKEN_HEADER_KEY = 'authentication-token';
  static AUTHORIZATION_HEADER_KEY = 'Authorization';
 
  constructor(
    private httpClient: HttpClient,
    private store: Store,
    private featureToggleService: FeatureToggleService
  ) {}
 
  /**
-  * sets the request header for the appropriate captcha service
-  * @param captcha captcha token for captcha V2 and V3
-  * @param captchaAction captcha action for captcha V3
-  */
  private appendCaptchaTokenToHeaders(captcha: string, captchaAction: string): MonoTypeOperatorFunction<HttpHeaders> {
    return map(headers =>
      // testing token gets 'null' from captcha service, so we accept it as a valid value here
      captchaAction !== undefined
        ? // captcha V3
          headers.set(ApiService.AUTHORIZATION_HEADER_KEY, `CAPTCHA recaptcha_token=${captcha} action=${captchaAction}`)
        : // captcha V2
          // second parameter 'foo=bar' is only required to resolve a shortcoming of the server side implementation that requires two parameters
          headers.set(ApiService.AUTHORIZATION_HEADER_KEY, `CAPTCHA g-recaptcha-response=${captcha} foo=bar`)
    );
  }
 
  /**
   * merges supplied and default headers
   */
  private constructHeaders(options?: AvailableOptions): Observable<HttpHeaders> {
    const defaultHeaders = new HttpHeaders().set('content-type', 'application/json').set('Accept', 'application/json');
 
    return of(
      options?.headers
        ? // append incoming headers to default ones
          options.headers.keys().reduce((acc, key) => acc.set(key, options.headers.get(key)), defaultHeaders)
        : // just use default headers
          defaultHeaders
    ).pipe(
      // testing token gets 'null' from captcha service, so we accept it as a valid value here
      options?.captcha?.captcha !== undefined
        ? // captcha headers
          this.appendCaptchaTokenToHeaders(options.captcha.captcha, options.captcha.captchaAction)
        : identity
    );
  }
 
  private handleErrors<T>(dispatch: boolean): MonoTypeOperatorFunction<T> {
    return catchError(error => {
      if (dispatch) {
        if (error.status === 0) {
          this.store.dispatch(communicationTimeoutError({ error }));
          return EMPTY;
        } else if (error.status >= 500 && error.status < 600) {
          this.store.dispatch(serverError({ error }));
          return EMPTY;
        }
      }
      return throwError(() => error);
    });
  }
 
  private execute<T>(options: AvailableOptions, httpCall$: Observable<T>): Observable<T> {
    return httpCall$.pipe(this.handleErrors(!options?.skipApiErrorHandling));
  }
 
  constructUrlForPath(path: string, options?: AvailableOptions): Observable<string> {
    if (path.startsWith('http://') || path.startsWith('https://')) {
      return of(path);
    }
    return combineLatest([
      this.store.pipe(select(getRestEndpoint), whenTruthy()),
      this.getLocale$(options),
      this.getCurrency$(options),
      of('/'),
      of(path.includes('/') ? path.split('/')[0] : path),
      // pgid
      this.store.pipe(
        select(getPGID),
        map(pgid => (options?.sendPGID && pgid ? `;pgid=${pgid}` : options?.sendSPGID && pgid ? `;spgid=${pgid}` : ''))
      ),
      // remaining path
      of(path.includes('/') ? path.substring(path.indexOf('/')) : ''),
    ]).pipe(
      first(),
      map(arr => arr.join(''))
    );
  }
 
  private getLocale$(options: AvailableOptions): Observable<string> {
    return options?.sendLocale === undefined || options.sendLocale
      ? this.store.pipe(
          select(isServerConfigurationLoaded),
          whenTruthy(),
          switchMap(() =>
            this.store.pipe(
              select(getCurrentLocale),
              whenTruthy(),
              map(l => `;loc=${l}`)
            )
          )
        )
      : of('');
  }
 
  private getCurrency$(options: AvailableOptions): Observable<string> {
    return options?.sendCurrency === undefined || options.sendCurrency
      ? this.store.pipe(
          select(isServerConfigurationLoaded),
          whenTruthy(),
          switchMap(() =>
            this.store.pipe(
              select(getCurrentCurrency),
              whenTruthy(),
              map(l => `;cur=${l}`)
            )
          )
        )
      : of('');
  }
 
  private constructHttpClientParams(
    path: string,
    options?: AvailableOptions
  ): Observable<[string, { headers: HttpHeaders; params: HttpParams }]> {
    return forkJoin([
      this.constructUrlForPath(path, options),
      defer(() =>
        this.constructHeaders(options).pipe(
          map(headers => ({
            headers,
            params: options?.params,
            responseType: options?.responseType,
          }))
        )
      ),
    ]);
  }
 
  /**
   * http get request
   */
  get<T>(path: string, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.get<T>(url, httpOptions))
      )
    );
  }
 
  /**
   * http options request
   */
  options<T>(path: string, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.options<T>(url, httpOptions))
      )
    );
  }
 
  /**
   * http put request
   */
  put<T>(path: string, body = {}, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.put<T>(url, body, httpOptions))
      )
    );
  }
 
  /**
   * http patch request
   */
  patch<T>(path: string, body = {}, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.patch<T>(url, body, httpOptions))
      )
    );
  }
 
  /**
   * http post request
   */
  post<T>(path: string, body = {}, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.post<T>(url, body, httpOptions))
      )
    );
  }
 
  /**
   * http delete request
   */
  delete<T>(path: string, options?: AvailableOptions): Observable<T> {
    return this.execute(
      options,
      this.constructHttpClientParams(path, options).pipe(
        concatMap(([url, httpOptions]) => this.httpClient.delete<T>(url, httpOptions))
      )
    );
  }
 
  /**
   * Pipeable operator for link translation (resolving one single link).
   *
   * @returns The link resolved to its actual REST response data.
   */
  resolveLink<T>(options?: AvailableOptions): OperatorFunction<Link, T> {
    return stream$ =>
      stream$.pipe(
        withLatestFrom(this.store.pipe(select(getICMServerURL))),
        concatMap(([link, icmServerURL]) =>
          iif(
            // check if link data is properly formatted
            () => link?.type === 'Link' && !!link.uri,
            // flat map to API request
            this.get<T>(`${icmServerURL}/${link.uri}`, options),
            // throw if link is not properly supplied
            throwError(() => new Error('link was not properly formatted'))
          )
        )
      );
  }
 
  /**
   * Pipeable operator for link translation (resolving multiple links).
   *
   * @returns The links resolved to their actual REST response data.
   */
  resolveLinks<T>(options?: AvailableOptions): OperatorFunction<Link[], T[]> {
    return source$ =>
      source$.pipe(
        // filter for all real Link elements
        map(links => links.filter(el => el?.type === 'Link' && !!el.uri)),
        withLatestFrom(this.store.pipe(select(getICMServerURL))),
        // transform Link elements to API Observables
        map(([links, icmServerURL]) => links.map(item => this.get<T>(`${icmServerURL}/${item.uri}`, options))),
        // flatten to API requests O<O<T>[]> -> O<T[]>
        concatMap(obsArray => iif(() => !!obsArray.length, forkJoin(obsArray), of([])))
      );
  }
 
  /**
   * To support special characters (slash, percent and plus char) of user defined URI Components (like login, email, ...).
   * This method encodes a given resource ID in a way that can be processed by ICM.
   * REST API of ICM version pre 12.0 encode the URI components twice, because of former restriction of the httpd.
   *
   * @param resourceId    The resource ID to be encoded.
   * @returns             The encoded resource ID.
   */
  encodeResourceId(resourceId: string): string {
    return this.featureToggleService.enabled('legacyEncoding')
      ? // ICM 7.10 & ICM 11 resource ID encoding
        encodeURIComponent(encodeURIComponent(resourceId))
      : // ICM 12 and above resource ID encoding
        // encodeURIComponent replaces spaces with '+' that's not RFC conform.
        // Therefore, we encode existing '+' with '%2B', converting the string with encodeURIComponent,
        // and converting '%2B' ('%252B' after encodeURIComponent) to '+' back.
        encodeURIComponent(resourceId?.replaceAll('+', '%2B'))?.replaceAll('\\+', '%20')?.replaceAll('%252B', '+');
  }
 
  /**
   * Method to generate a B2B user endpoint prefix based on the currently logged in user and customer.
   */
  b2bUserEndpoint() {
    const ids$ = combineLatest([
      this.store.pipe(select(getLoggedInUser)),
      this.store.pipe(select(getLoggedInCustomer)),
    ]).pipe(
      filter(([user, customer]) => !!user && !!customer),
      take(1)
    );
 
    return {
      get: <T>(path: string, options?: AvailableOptions) =>
        ids$.pipe(
          concatMap(([user, customer]) =>
            this.get<T>(
              `customers/${this.encodeResourceId(customer.customerNo)}/users/${this.encodeResourceId(
                user.login
              )}/${path}`,
              options
            )
          )
        ),
      delete: <T>(path: string, options?: AvailableOptions) =>
        ids$.pipe(
          concatMap(([user, customer]) =>
            this.delete<T>(
              `customers/${this.encodeResourceId(customer.customerNo)}/users/${this.encodeResourceId(
                user.login
              )}/${path}`,
              options
            )
          )
        ),
      put: <T>(path: string, body = {}, options?: AvailableOptions) =>
        ids$.pipe(
          concatMap(([user, customer]) =>
            this.put<T>(
              `customers/${this.encodeResourceId(customer.customerNo)}/users/${this.encodeResourceId(
                user.login
              )}/${path}`,
              body,
              options
            )
          )
        ),
      patch: <T>(path: string, body = {}, options?: AvailableOptions) =>
        ids$.pipe(
          concatMap(([user, customer]) =>
            this.patch<T>(
              `customers/${this.encodeResourceId(customer.customerNo)}/users/${this.encodeResourceId(
                user.login
              )}/${path}`,
              body,
              options
            )
          )
        ),
      post: <T>(path: string, body = {}, options?: AvailableOptions) =>
        ids$.pipe(
          concatMap(([user, customer]) =>
            this.post<T>(
              `customers/${this.encodeResourceId(customer.customerNo)}/users/${this.encodeResourceId(
                user.login
              )}/${path}`,
              body,
              options
            )
          )
        ),
    };
  }
 
  /**
   * Basket REST API wrapper to work with the currently selected basket id or 'current' as fallback.
   */
  currentBasketEndpoint() {
    const basketUrl$ = this.store
      .pipe(
        select(getBasketIdOrCurrent),
        map(basketId => `baskets/${basketId}`)
      )
      .pipe(take(1));
 
    return {
      get: <T>(path: string, options?: AvailableOptions) =>
        basketUrl$.pipe(concatMap(basketUrl => this.get<T>(path ? `${basketUrl}/${path}` : basketUrl, options))),
      delete: <T>(path: string, options?: AvailableOptions) =>
        basketUrl$.pipe(concatMap(basketUrl => this.delete<T>(path ? `${basketUrl}/${path}` : basketUrl, options))),
      put: <T>(path: string, body = {}, options?: AvailableOptions) =>
        basketUrl$.pipe(concatMap(basketUrl => this.put<T>(path ? `${basketUrl}/${path}` : basketUrl, body, options))),
      patch: <T>(path: string, body = {}, options?: AvailableOptions) =>
        basketUrl$.pipe(
          concatMap(basketUrl => this.patch<T>(path ? `${basketUrl}/${path}` : basketUrl, body, options))
        ),
      post: <T>(path: string, body = {}, options?: AvailableOptions) =>
        basketUrl$.pipe(concatMap(basketUrl => this.post<T>(path ? `${basketUrl}/${path}` : basketUrl, body, options))),
    };
  }
}