import { Observable } from "rxjs/Observable"; import { SessionStorage } from "../SessionStorage"; import { HttpClient } from "@angular/common/http"; export class AuthedApi { constructor(protected http: HttpClient, private matrixAuth = false) { } protected authedGet(url: string, qs?: any): Observable { const opts = this.fillAuthOptions(null, qs, null); return this.http.get(url, opts); } protected authedPost(url: string, body?: any): Observable { if (!body) body = {}; const opts = this.fillAuthOptions(null, null, null); return this.http.post(url, body, opts); } protected authedPut(url: string, body?: any): Observable { if (!body) body = {}; const opts = this.fillAuthOptions(null, null, null); return this.http.put(url, body, opts); } protected authedDelete(url: string, qs?: any): Observable { const opts = this.fillAuthOptions(null, qs, null); return this.http.delete(url, opts); } private fillAuthOptions(opts: any, qs: any, headers: any): { headers: any, params: any } { if (!opts) opts = {}; if (!qs) qs = {}; if (!headers) headers = {}; if (this.matrixAuth) { headers["Authorization"] = `Bearer ${SessionStorage.scalarToken}`; } else { qs["scalar_token"] = SessionStorage.scalarToken; } return Object.assign({}, opts, {params: qs, headers: headers}); } }