make it work with xhr

This commit is contained in:
Bruno Windels 2020-10-26 17:37:32 +01:00
parent ee1e62207c
commit a3aa25449b
2 changed files with 18 additions and 10 deletions

View file

@ -55,7 +55,7 @@ export class MediaRepository {
async downloadEncryptedFile(fileEntry) {
const url = this.mxcUrl(fileEntry.url);
const {body: encryptedBuffer} = await this._request(url, {format: "buffer", cache: true}).response();
const {body: encryptedBuffer} = await this._request(url, {method: "GET", format: "buffer", cache: true}).response();
const decryptedBuffer = await decryptAttachment(this._crypto, encryptedBuffer, fileEntry);
return decryptedBuffer;
}

View file

@ -35,19 +35,22 @@ class RequestResult {
}
}
function send(url, options) {
function send(url, {method, headers, timeout, body, format}) {
const xhr = new XMLHttpRequest();
xhr.open(options.method, url);
if (options.headers) {
for(const [name, value] of options.headers.entries()) {
if (format === "buffer") {
xhr.responseType = "arraybuffer";
}
xhr.open(method, url);
if (headers) {
for(const [name, value] of headers.entries()) {
xhr.setRequestHeader(name, value);
}
}
if (options.timeout) {
xhr.timeout = options.timeout;
if (timeout) {
xhr.timeout = timeout;
}
xhr.send(options.body || null);
xhr.send(body || null);
return xhr;
}
@ -62,12 +65,17 @@ function xhrAsPromise(xhr, method, url) {
}
export function xhrRequest(url, options) {
url = addCacheBuster(url);
const {cache, format} = options;
if (!cache) {
url = addCacheBuster(url);
}
const xhr = send(url, options);
const promise = xhrAsPromise(xhr, options.method, url).then(xhr => {
const {status} = xhr;
let body = null;
if (xhr.getResponseHeader("Content-Type") === "application/json") {
if (format === "buffer") {
body = xhr.response;
} else if (xhr.getResponseHeader("Content-Type") === "application/json") {
body = JSON.parse(xhr.responseText);
}
return {status, body};