All files / app/services/log/publishers/local-storage log-local-storage.ts

100% Statements 16/16
100% Branches 5/5
100% Functions 4/4
100% Lines 16/16

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                          963x     963x 963x                         641x 9x   641x                   656x     656x   656x         656x     656x     650x       6x     656x         6x 6x      
import { Observable, of } from 'rxjs';
import { IEnvironment } from 'src/environments/interface/ienvironment';
import { LogPublisher } from '../publisher/log-publisher';
import { LogEntry } from '../../logEntry/logEntry';
 
/** Local storage {@link LogPublisher}. Used to log in local storage. */
export class LogLocalStorage extends LogPublisher {
  /** Max number of elements in local storage */
  maxSize;
 
  /** Log local storage publisher constructor. */
  constructor(environment: IEnvironment) {
    // Must call `super()`from derived classes
    super();
 
    // Set location
    this.location = 'logging';
    this.maxSize = environment.production ? 100 : 1000;
  }
 
  /**
   * Push a {@link LogEntry} in an array if the array is small enough, but shift
   * all the values otherwise. Used to ensure the localStorage size doesn't
   * increase above the set limit.
   *
   * @param values The array of {@link LogEntry}
   * @param entry The {@link LogEntry} to push at the end of the array, after a
   *   shift if necessary
   */
  pushOrShift(values: LogEntry[], entry: LogEntry) {
    if (values.length >= this.maxSize) {
      values.shift();
    }
    values.push(entry);
  }
 
  /**
   * Method used to actually log a {@link LogEntry}. Returns
   *
   * @param entry The {@link LogEntry} to log
   * @returns A boolean indicating if the entry was logged.
   */
  log(entry: LogEntry): Observable<boolean> {
    let ret = false;
    let values: LogEntry[];
 
    try {
      // Get previous values from local storage
      values = localStorage.getItem(this.location)
        ? JSON.parse(localStorage.getItem(this.location) as string)
        : [];
 
      // Add new log entry to array
      this.pushOrShift(values, entry);
 
      // Store array into local storage
      localStorage.setItem(this.location, JSON.stringify(values, null, '\n'));
 
      // Set return value
      ret = true;
    } catch (ex) {
      // Display error in console
      // eslint-disable-next-line no-console
      console.log(ex);
    }
 
    return of(ret);
  }
 
  /** Method used to clear the local storage */
  clear(): Observable<boolean> {
    localStorage.removeItem(this.location);
    return of(true);
  }
}