moya-locale.service.ts 1.84 KB
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {MoyaLocale} from './moya-locale.model';
import {MOYA_BASE_URL, MoyaRestTool} from '../../shared/tools/moya-rest.tool';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/catch';

export const DEFAULT_LOCALE = 'fi';
const LOCALSTORAGE_NAME = 'currently used locale code';

@Injectable()
export class MoyaLocaleService {
  constructor(private http: HttpClient) { }

  /**
   * Order of Locale:
   * 1. User's locale from database
   * 2. User's locale from cookie
   * 3. Event's locale from database
   * 4. Default
   *
   * @return {Observable<string>} Return current locale as a string. No errors.
   */
  public getUserLocale(): Observable<string> {

    return this.http.get<MoyaLocale>(MOYA_BASE_URL + '/v3/locale/')
      .catch(x => Observable.of({} as MoyaLocale))
      .map(locale => {
        if (locale && locale.userLocale) {
          return locale.userLocale;
        }

        const storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);

        if (storageLocale) {
          return storageLocale;
        }

        if (locale.eventLocale) {
          return locale.eventLocale;
        }

        return DEFAULT_LOCALE;
      });
  }


  /**
   * Store user's locale. This will store it to server.  Or server is not available, into localstorage.
   *
   * There is no errors
   * @param {string} locale
   */
  public setUserLocale(locale: string): void {

    const newLocale: MoyaLocale = {
      userLocale: locale,
      eventLocale: undefined
    };

    // let's save locale to database, if it fails, we save it into localstorage. No errors to show for user.
    this.http.post(MOYA_BASE_URL + '/v3/locale/', newLocale).catch(x => {
      localStorage.setItem(LOCALSTORAGE_NAME, locale);
      return 'ok';
    }).subscribe();
  }
}