extract map -> formdata conversion and also suppor this for xhr

This commit is contained in:
Bruno Windels 2022-06-15 10:15:15 +02:00
parent a644621889
commit 4caabae895
3 changed files with 21 additions and 14 deletions

View File

@ -27,6 +27,21 @@ export function addCacheBuster(urlStr, random = Math.random) {
return urlStr + `_cacheBuster=${Math.ceil(random() * Number.MAX_SAFE_INTEGER)}`;
}
export function mapAsFormData(map) {
const formData = new FormData();
for (const [name, value] of map) {
let filename;
// Special case {name: string, blob: BlobHandle} to set a filename.
// This is the format returned by platform.openFile
if (value.blob?.nativeBlob && value.name) {
formData.set(name, value.blob.nativeBlob, value.name);
} else {
formData.set(name, value);
}
}
return formData;
}
export function tests() {
return {
"add cache buster": assert => {

View File

@ -20,7 +20,7 @@ import {
ConnectionError
} from "../../../../matrix/error.js";
import {abortOnTimeout} from "../../../../utils/timeout";
import {addCacheBuster} from "./common.js";
import {addCacheBuster, mapAsFormData} from "./common.js";
import {xhrRequest} from "./xhr.js";
class RequestResult {
@ -71,18 +71,7 @@ export function createFetchRequest(createTimeout, serviceWorkerHandler) {
body = body.nativeBlob;
}
if (body instanceof Map) {
const formData = new FormData();
for (const [name, value] of body) {
let filename;
// Special case {name: string, blob: BlobHandle} to set a filename.
// This is the format returned by platform.openFile
if (value.blob?.nativeBlob && value.name) {
formData.set(name, value.blob.nativeBlob, value.name);
} else {
formData.set(name, value);
}
}
body = formData;
body = mapAsFormData(body);
}
let options = {method, body};
if (controller) {

View File

@ -18,7 +18,7 @@ import {
AbortError,
ConnectionError
} from "../../../../matrix/error.js";
import {addCacheBuster} from "./common.js";
import {addCacheBuster, mapAsFormData} from "./common.js";
class RequestResult {
constructor(promise, xhr) {
@ -94,6 +94,9 @@ export function xhrRequest(url, options) {
if (body?.nativeBlob) {
body = body.nativeBlob;
}
if (body instanceof Map) {
body = mapAsFormData(body);
}
xhr.send(body || null);
return new RequestResult(promise, xhr);