all files / src/app/services/ page.service.ts

100% Statements 97/97
95.45% Branches 42/44
100% Functions 27/27
100% Lines 95/95
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                       161×                                 161× 161× 161× 161× 161× 161× 161× 161× 161× 161× 161× 161× 161×                 314×             46×                 205× 205× 205× 205×   199×               17×             52×       52×                 3374× 3374×   3374×     3522× 536×                                                             3509× 3509×   3509×     3509× 9482× 9482× 9482× 26×     9482×     3560×                                 3340× 3340× 3605× 2925× 680× 680× 176×     504× 504×         3340×                             5082× 5082× 2268× 2268×         2268× 2268× 1068× 1068× 1068× 1068×             1200× 924×           276×                 2268×     2814×                       2925× 2925×     2925×     264× 264×         264×   200× 200× 200× 200× 200×       64× 64×         2661×            
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable, LOCALE_ID, NgZone, Renderer2, RendererFactory2 } from '@angular/core';
import { AngularFirestore, QueryFn } from '@angular/fire/firestore';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { ParamMap, Router } from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { map, share, startWith, tap } from 'rxjs/operators';
import { routerLinksEN, routerLinksTR } from '../app-config';
import { PageBaseModel, RouterLinksModel } from '../models';
import { AlertService } from './alert.service';
import { CarouselService } from './carousel.service';
import { SeoService } from './seo.service';
 
/**
 * Page Service
 */
@Injectable()
export class PageService {
    /** locale */
    locale: string;
    /** translated router links */
    routerLinks: RouterLinksModel;
    /** collection of PageBaseModel */
    private readonly page$ = new Subject<PageBaseModel>();
    /** Renderer2 */
    private readonly renderer: Renderer2;
 
    /**
     * constructor of PageService
     * @param seo: SeoService
     * @param carouselService: CarouselService
     * @param alert: AlertService
     * @param state: TransferState
     * @param afs: AngularFirestore
     * @param router: Router
     * @param ngZone: NgZone
     * @param rendererFactory: RendererFactory2
     * @param document: DOCUMENT
     * @param localeP: LOCALE_ID
     */
    constructor(public seo: SeoService,
                public carouselService: CarouselService,
                private readonly alert: AlertService,
                private readonly state: TransferState,
                private readonly afs: AngularFirestore,
                public router: Router,
                private readonly ngZone: NgZone,
                private readonly rendererFactory: RendererFactory2,
                @Inject(DOCUMENT) private readonly document,
                @Inject(LOCALE_ID) private readonly localeP: string) {
        this.locale = localeP === 'tr' ? 'tr-TR' : 'en-US'; // TODO: fix for other locales, this is quick fix to force to use with culture codes
        this.renderer = rendererFactory.createRenderer(undefined, undefined);
        this.routerLinks = this.locale === 'tr-TR' ? routerLinksTR : routerLinksEN;
    }
 
    /**
     * track content object array by index
     * @param index: index no
     * @param item: object
     */
    trackByIndex(index, item): number {
        return index;
    }
 
    /**
     * get current PageBaseModel
     */
    getPage(): Observable<PageBaseModel> {
        return this.page$.asObservable()
            .pipe(share());
    }
 
    /**
     * init page html tags and content
     * @param page: PageBaseModel
     */
    initPage(page: PageBaseModel): void {
        this.page$.next(page);
        this.seo.setSEOData(page);
        this.carouselService.init(page.carousel);
        if (page.backgroundCoverImage) {
            this.renderer.setStyle(this.document.body, 'background-image', `url(${page.backgroundCoverImage.src})`);
        } else {
            this.renderer.setStyle(this.document.body, 'background-image', '');
        }
    }
 
    /**
     * get route path of current page; sample: '/articles/1' will return as '/articles'
     */
    getRoutePath(): string {
        return `/${this.getRoutePathName()}`;
    }
 
    /**
     * get route path name of current page; sample: '/articles/1' will return as 'articles'
     */
    getRoutePathName(): string {
        const currentURLParts = this.router.url.trim()
            .split('?')[0]
            .split('/');
 
        return currentURLParts[1].trim(); // currentURLParts.length is always greater than 1 because it always starts with a '/'
    }
 
    /**
     * get document from firestore
     * @param type: type of page
     * @param path: path of document to load from Firestore
     */
    getDocumentFromFirestore<T>(type: new() => T, path: string): Observable<T> {
        const ssrPageKey = makeStateKey<any>(`ssr_page_${path}`);
        const existPage = this.state.get(ssrPageKey, undefined);
 
        return this.afs.doc<T>(path)
            .valueChanges()
            .pipe(tap(pageItem => {
                    if (pageItem) {
                        this.state.set(ssrPageKey, pageItem);
                    }
                }),
                existPage ? startWith(existPage) : tap()
            )
            .pipe(share());
    }
 
    /**
     * get collection from firestore
     * @param path: path of collection to load from Firestore
     * @param queryFn: QueryFn
     * @param uniqueKey: unique key for TransferState, if path is already unique without order and limit, no need to use this
     */
    getCollectionFromFirestore<T>(path: string, queryFn?: QueryFn, uniqueKey?: any): Observable<Array<T>> {
        const ssrCollectionKey = makeStateKey<any>(`ssr_collection_${uniqueKey ? uniqueKey : ''}_${path}`);
        const existPage = this.state.get(ssrCollectionKey, undefined);
 
        return this.afs.collection<T>(path, queryFn)
            .valueChanges()
            .pipe(tap(docs => {
                    this.state.set(ssrCollectionKey, docs);
                }),
                existPage ? startWith(existPage) : tap()
            )
            .pipe(share());
    }
 
    /**
     * get collection of content from firestore
     * @param path: path of collection to load from Firestore
     * @param queryFn: QueryFn
     * @param uniqueKey: unique key for TransferState, if path is already unique without order and limit, no need to use this
     */
    getCollectionOfContentFromFirestore<T>(path: string, queryFn?: QueryFn, uniqueKey?: any): Observable<Array<T>> {
        const ssrCollectionKey = makeStateKey<any>(`ssr_collection_${uniqueKey ? uniqueKey : ''}_${path}`);
        const existPage = this.state.get(ssrCollectionKey, undefined);
 
        return this.afs.collection(path, queryFn)
            .snapshotChanges()
            .pipe(map(actions =>
                actions.map(action => {
                    const id = action.payload.doc.id;
                    const data = action.payload.doc.data() as PageBaseModel;
                    if (!data.hasOwnProperty('contentSummary')) {
                        data.contentSummary = data.content;
                    }
 
                    return {id, ...data};
                })))
            .pipe(tap(docs => {
                    this.state.set(ssrCollectionKey, docs);
                }),
                existPage ? startWith(existPage) : tap()
            )
            .pipe(share());
    }
 
    /**
     * get page from firestore
     * @param type: type of page
     * @param pathOfCollectionWithoutLocalePart: main collection path of firestore;
     * used in: `${pathOfCollectionWithoutLocalePart}_${this.locale}`
     * @param pageID: page id on firestore; you can keep undefined, if you want to get pageID from 'router.url'
     */
    getPageFromFirestore<T extends PageBaseModel>(type: new() => T,
                                                  pathOfCollectionWithoutLocalePart: string,
                                                  pageID: string): Observable<T> {
        const pageBase$ = this.getDocumentFromFirestore(type, `${pathOfCollectionWithoutLocalePart}_${this.locale}/${pageID}`);
        pageBase$.subscribe(page => {
            if (page === undefined) {
                this.redirectToTranslationOr404(pathOfCollectionWithoutLocalePart, pageID);
            } else Eif (page.routePath) {
                if (this.router.url.startsWith(page.routePath)) {
                    this.initPage(page);
                } else {
                    // redirect to origin route path for seo
                    const languageCode2 = this.locale.substring(0, 2);
                    this.seo.http301(`/${languageCode2}/${page.routePath}/${pageID}`, true);
                }
            }
        });
 
        return pageBase$;
    }
 
    /**
     * check to redirect by id param, if redirected a page; true will be returned otherwise false will be returned
     * @param pmap: ParamMap
     * @param pathOfCollectionWithoutLocalePart: main collection path of firestore;
     * used in: `${pathOfCollectionWithoutLocalePart}_${this.locale}`
     * @param pathOfListPage: path of list page; sample: '/articles'
     * @param pathOfDetailPage: path of detail page; sample: '/article'
     */
    checkToRedirectByIDParam(pmap: ParamMap,
                             pathOfCollectionWithoutLocalePart: string,
                             pathOfListPage: string,
                             pathOfDetailPage: string): boolean {
        const pID = Number(pmap.get('id'));
        if (pID || pID === 0) {
            this.afs.collection(`${pathOfCollectionWithoutLocalePart}_${this.locale}`,
                ref => ref.where('orderNo', '==', pID)
                    .limit(1)
            )
                .snapshotChanges()
                .subscribe(data => {
                    this.ngZone.run(() => {
                        if (data && data.length > 0) {
                            data.map(pld => {
                                const pageItem = pld.payload.doc.data() as PageBaseModel;
                                this.ngZone.run(() => {
                                    this.router.navigate([pageItem.routePath, pld.payload.doc.id])
                                        .catch(// istanbul ignore next
                                            reason => {
                                                this.alert.error(reason);
                                            });
                                });
                            });
                        } else if (pID === 0) {
                            this.router.navigate([pathOfListPage])
                                .catch(// istanbul ignore next
                                    reason => {
                                        this.alert.error(reason);
                                    });
                        } else {
                            this.router.navigate([pathOfDetailPage, pID + 1])
                                .catch(// istanbul ignore next
                                    reason => {
                                        this.alert.error(reason);
                                    });
                        }
                    });
                });
 
            return true;
        }
 
        return false;
    }
 
    /**
     * check if there is translation by pageID on other locale and redirect to correct pageID by requested locale
     * if there is no record on other locale by pageID, page will be redirected to http-404
     * @param pathOfCollectionWithoutLocalePart: main collection path of firestore;
     * used in: `${pathOfCollectionWithoutLocalePart}_${this.locale}`
     * @param pageID: page id on firestore
     */
    redirectToTranslationOr404(pathOfCollectionWithoutLocalePart: string, pageID: string): void {
        // try to find pageID in other locale
        const checkInLocale = this.locale === 'en-US' ? 'tr-TR' : 'en-US';
        this.afs.doc<PageBaseModel>(`${pathOfCollectionWithoutLocalePart}_${checkInLocale}/${pageID}`)
            .valueChanges()
            .subscribe(pageItem => {
                if (pageItem) {
                    // found in other locale
                    // so try to find requested page in requested locale by i18nKey
                    this.afs.collection<PageBaseModel>(`${pathOfCollectionWithoutLocalePart}_${this.locale}`,
                        ref => ref.where('i18nKey', '==', pageItem.i18nKey)
                            .limit(1)
                    )
                        .snapshotChanges()
                        .subscribe(data => {
                            if (data && data.length > 0) {
                                // page in found in requested locale by i18nKey
                                data.map(pld => {
                                    const id = pld.payload.doc.id;
                                    const requestedPageItem = pld.payload.doc.data();
                                    const languageCode2 = this.locale.substring(0, 2);
                                    this.seo.http301(`/${languageCode2}/${requestedPageItem.routePath}/${id}`, true);
                                });
                            } else {
                                // there is no translation by i18nKey, so redirect to correct locale
                                const languageCode2 = checkInLocale.substring(0, 2);
                                this.seo.http301(`/${languageCode2}/${pageItem.routePath}/${pageID}`, true);
                            }
                        });
                } else {
                    // not found also in other locale
                    this.seo.http404();
                }
            });
    }
 
}