fix errors & support login in network

This commit is contained in:
Bruno Windels 2019-02-04 22:26:24 +00:00
parent b6df30bc27
commit b15136a9e8

View file

@ -1,4 +1,4 @@
class Request {
class RequestWrapper {
constructor(promise, controller) {
this._promise = promise;
this._controller = controller;
@ -8,37 +8,45 @@ class Request {
this._controller.abort();
}
get response() {
response() {
return this._promise;
}
}
export class Network {
export default class Network {
constructor(homeserver, accessToken) {
this._homeserver = homeserver;
this._accessToken = accessToken;
}
_url(csPath) {
return `${this._homeserver}/_matrix/client/r0/${csPath}`;
return `${this._homeserver}/_matrix/client/r0${csPath}`;
}
_request(method, csPath, queryParams = {}) {
_request(method, csPath, queryParams = {}, body) {
const queryString = Object.entries(queryParams)
.filter(([name, value]) => value !== undefined)
.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`);
.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)
.join("&");
const url = this._url(`${csPath}?${queryString}`);
const request = new Request(url);
const headers = request.headers;
let bodyString;
const headers = new Headers();
if (this._accessToken) {
headers.append("Authorization", `Bearer ${this._accessToken}`);
}
headers.append("Accept", "application/json");
if (false/* body */) {
if (body) {
headers.append("Content-Type", "application/json");
bodyString = JSON.stringify(body);
}
const controller = new AbortController();
// TODO: set authenticated headers with second arguments, cache them
let promise = fetch(request, {signal: controller.signal});
let promise = fetch(url, {
method,
headers,
body: bodyString,
signal: controller.signal
});
promise = promise.then(response => {
if (response.ok) {
return response.json();
@ -49,10 +57,29 @@ export class Network {
}
}
});
return new Request(promise, controller);
return new RequestWrapper(promise, controller);
}
_post(csPath, queryParams, body) {
return this._request("POST", csPath, queryParams, body);
}
_get(csPath, queryParams, body) {
return this._request("GET", csPath, queryParams, body);
}
sync(timeout = 0, since = undefined) {
return this._request("GET", "/sync", {since, timeout});
return this._get("/sync", {since, timeout});
}
passwordLogin(username, password) {
return this._post("/login", undefined, {
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": username
},
"password": password
});
}
}