matrix-dimension/web/app/shared/services/authed-api.ts

43 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Observable } from "rxjs/Observable";
2017-12-23 04:08:10 +00:00
import { SessionStorage } from "../SessionStorage";
2019-06-29 06:21:56 +00:00
import { HttpClient } from "@angular/common/http";
export class AuthedApi {
2019-07-11 04:10:10 +00:00
constructor(protected http: HttpClient, private matrixAuth = false) {
}
2019-06-29 06:21:56 +00:00
protected authedGet<T>(url: string, qs?: any): Observable<T> {
2019-07-01 05:05:33 +00:00
const opts = this.fillAuthOptions(null, qs, null);
return this.http.get<T>(url, opts);
}
2019-06-29 06:21:56 +00:00
protected authedPost<T>(url: string, body?: any): Observable<T> {
if (!body) body = {};
2019-07-01 05:05:33 +00:00
const opts = this.fillAuthOptions(null, null, null);
return this.http.post<T>(url, body, opts);
}
2019-07-06 21:19:27 +00:00
protected authedPut<T>(url: string, body?: any): Observable<T> {
if (!body) body = {};
const opts = this.fillAuthOptions(null, null, null);
return this.http.put<T>(url, body, opts);
}
2019-06-29 06:21:56 +00:00
protected authedDelete<T>(url: string, qs?: any): Observable<T> {
2019-07-01 05:05:33 +00:00
const opts = this.fillAuthOptions(null, qs, null);
return this.http.delete<T>(url, opts);
}
private fillAuthOptions(opts: any, qs: any, headers: any): { headers: any, params: any } {
if (!opts) opts = {};
if (!qs) qs = {};
2019-07-01 05:05:33 +00:00
if (!headers) headers = {};
2019-07-11 04:10:10 +00:00
if (this.matrixAuth) {
2019-07-01 05:05:33 +00:00
headers["Authorization"] = `Bearer ${SessionStorage.scalarToken}`;
} else {
qs["scalar_token"] = SessionStorage.scalarToken;
}
return Object.assign({}, opts, {params: qs, headers: headers});
}
}