All files / app/service/api ref.service.ts

37.17% Statements 29/78
45.45% Branches 15/33
22.85% Functions 8/35
34.32% Lines 23/67

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  128x         128x 128x   128x 128x       128x         190x   190x     190x 190x 190x 190x   190x 190x               24x                   1x                                   9x               9x                                                 24x 23x 20x   23x       20x                                                                                                                                                                
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { delay } from 'lodash-es';
import { autorun } from 'mobx';
import { catchError, concat, first, map, Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { mapPage, Page } from '../../model/page';
import { mapRef, Ref, RefFilter, RefPageArgs, writeEdit, writeRef } from '../../model/ref';
import { Store } from '../../store/store';
import { params } from '../../util/http';
import { escapePath, OpPatch } from '../../util/json-patch';
import { ConfigService } from '../config.service';
import { LoginService } from '../login.service';
 
export const REF_CACHE_MS = 15 * 60 * 1000;
 
@Injectable({
  providedIn: 'root',
})
export class RefService {
 
  private _cache = new Map<string, boolean>();
 
  constructor(
    private http: HttpClient,
    private config: ConfigService,
    private store: Store,
    private login: LoginService,
  ) {
    autorun(() => {
      Iif (this.store.eventBus.event === 'reload') {
        this.store.eventBus.catchError$(this.get(this.store.eventBus.ref!.url, this.store.eventBus.ref!.origin!))
          .subscribe(ref => this.store.eventBus.refresh(ref));
      }
    });
  }
 
  private get base() {
    return this.config.api + '/api/v1/ref';
  }
 
  create(ref: Ref): Observable<string> {
    return this.http.post<string>(this.base, writeRef(ref)).pipe(
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  get(url: string, origin = ''): Observable<Ref> {
    return this.http.get(this.base, {
      params: params({ url, origin }),
    }).pipe(
      map(mapRef),
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  getCurrent(url: string): Observable<Ref> {
    return this.page({ url, size: 1 }).pipe(
      map(page => {
        if (!page.content.length) throw { status: 404 };
        return page.content[0];
      }),
    );
  }
 
  getDefaults(...tags: string[]): Observable<{ url: string, ref: Partial<Ref> } | undefined> {
    return concat(...[
      ...tags.map(t => this.getCurrent('tag:/' + t).pipe(
        catchError(err => of()),
      )),
      of(undefined),
    ]).pipe(
      first(),
      map(ref => {
        Eif (!ref) return ref;
        const url = ref.url;
        const partial: Partial<Ref> = ref;
        delete partial.url;
        delete partial.origin;
        delete partial.modified;
        delete partial.modifiedString;
        delete partial.created;
        delete partial.published;
        return { url, ref: partial };
      })
    );
  }
 
  exists(url: string, origin?: string): Observable<boolean> {
    const key = (origin || '') + ':' + url;
    if (this._cache.has(key)) return of(this._cache.get(key)!);
    delay(() => this._cache.delete(key), REF_CACHE_MS);
    return this.count({ url, query: origin }).pipe(
      map(n => !!n),
      tap(e => this._cache.set(key, e)),
    );
  }
 
  page(args?: RefPageArgs): Observable<Page<Ref>> {
    if (args?.query === '!@*') return of(Page.of<Ref>([]));
    if (args && args.obsolete === undefined) {
      args.obsolete = false;
    }
    return this.http.get(`${this.base}/page`, {
      params: params(args),
    }).pipe(
      map(mapPage(mapRef)),
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  count(args?: RefFilter): Observable<number> {
    if (args && args.obsolete === undefined) {
      args.obsolete = false;
    }
    return this.http.get(`${this.base}/count`, {
      responseType: 'text',
      params: params(args),
    }).pipe(
      map(parseInt),
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  update(ref: Ref): Observable<string> {
    return this.http.put<string>(this.base, writeRef(ref)).pipe(
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  getEditing(url: string): Observable<Ref | undefined> {
    if (!this.store.account.localTag) return of(undefined);
    return this.page({
      url,
      query: this.store.account.localTag + ':plugin/editing',
      size: 1,
      obsolete: null,
    }).pipe(
      map(page => page.content[0]),
      catchError(() => of(undefined)),
    );
  }
 
  startEditing(ref: Ref) {
    return this.create({
      url: ref.url,
      origin: this.store.account.origin,
      tags: [this.store.account.localTag, 'plugin/editing'],
      plugins: { 'plugin/editing': writeEdit(ref) }
    });
  }
 
  saveEdit(ref: Ref, cursor?: string): Observable<string> {
    if (!cursor) return this.startEditing(ref);
    return this.patch(ref.url, this.store.account.origin, cursor, [{
      op: 'add',
      path: '/plugins/' + escapePath('plugin/editing'),
      value: writeEdit(ref),
    }]);
  }
 
  patch(url: string, origin: string, cursor: string, patch: OpPatch[]): Observable<string> {
    return this.http.patch<string>(this.base, patch, {
      headers: { 'Content-Type': 'application/json-patch+json' },
      params: params({ url, origin, cursor }),
    }).pipe(
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  merge(url: string, origin: string, cursor: string, patch: Partial<Ref>): Observable<string> {
    return this.http.patch<string>(this.base, patch, {
      headers: { 'Content-Type': 'application/merge-patch+json' },
      params: params({ url, origin, cursor }),
    }).pipe(
      catchError(err => this.login.handleHttpError(err)),
    );
  }
 
  delete(url: string, origin = ''): Observable<void> {
    return this.http.delete<void>(this.base, {
      params: params({ url, origin }),
    }).pipe(
      catchError(err => this.login.handleHttpError(err)),
    );
  }
}