import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie'; import { UserConstants } from '@hdca/fe-angular-shared'; import { Observable } from 'rxjs/Observable'; import { production } from '../../tokens'; import { of } from 'rxjs'; @Injectable() export class TokenRefreshService { production: boolean; // TODO: Convert this to a service worker constructor(private http: HttpClient, private cookieService: CookieService, @Inject(production) productionDi) { this.production = productionDi; } refreshToken(defaultMinTimeToExpire = 50) { if (this.production && typeof document !== 'undefined' && this.getToken()) { const debounceTime = 2000; const tokenUrl = '/content/homedepot_ca/en_ca/.commerce.token.json'; const timeToExpire = Math.max(this.getTokenExpiry() + defaultMinTimeToExpire - new Date().valueOf(), defaultMinTimeToExpire); setTimeout(() => { return this.clientOnlyPostRequest(tokenUrl) .subscribe(result => { this.refreshToken(debounceTime); }); }, timeToExpire); } } getTokenExpiry(): number { if (typeof document !== 'undefined') { return Number(this.cookieService.get(UserConstants.EXPIRY) || 0); } else { return 0; } } getToken(): string { if (typeof document !== 'undefined') { return this.cookieService.get(UserConstants.UUID_KEY); } else { return ''; } } isCustomerLoggedIn() { if (typeof document !== 'undefined' && (this.cookieService.get(UserConstants.CUSTOMER_ID) || this.cookieService.get(UserConstants.EMAIL_KEY))) { return true; } else { return false; } } checkExpiry() { const expiry = this.getTokenExpiry(); const token = this.getToken(); if ((token && ((expiry <= Date.now()) || !this.isCustomerLoggedIn())) && this.production) { return this.refreshTokenOnce(); } else { return of('success'); } } refreshTokenOnce() { const tokenUrl = '/content/homedepot_ca/en_ca/.commerce.token.json'; return this.clientOnlyPostRequest(tokenUrl); } clientOnlyPostRequest(tokenUrl): Observable { return typeof window !== 'undefined' ? this.http.post(tokenUrl, {}) : of('success'); } }