I have to send a request to my rest API to send an element which contains an image file.
Here is the code calling the request function :
await uploader(async () => {
let mime = msg.fichier.split(";")[0].split(":")[1];
let data = atob(msg.fichier.split(",")[1]);
let bytes = new Uint8Array(data.length);
for (let i in data) {
bytes[i] = data.charCodeAt(i);
}
let file = new File(
[bytes],
msg.data.titre + "." + mime.split("/")[1],
{ type: mime }
);
return await upload_fichier(msg.type_fichier, file, { data: msg.data });
Below is the actual graphql request. My goal is to use api Rest request instead of graphql (i know graphql is better but for some reasons i NEED to use api Rest request) :
async function upload_fichier(type, fichier, variables) {
const body = new FormData();
variables[type] = null;
body.append(
"operations",
JSON.stringify({
query:
`mutation createElement($data: ElementInput!, $${type}: Upload) {
createElement(data: $data, ${type}: $${type}) {
element {
id
}
}
}`.replace(/\s\s+/g, " "),
variables: variables,
})
);
body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
body.append("1", fichier);
const storage = await browser.storage.local.get("refresh_token");
const headers = {};
if (storage.refresh_token) {
headers.authorization = "JWT " + storage.refresh_token;
}
const res = await fetch(url_graphql, {
method: "POST",
headers: headers,
body: body,
});
return await res.json();
Below is the code i tried to write to do what i want :
async function upload_fichier(type, fichier, variables) {
const body = new FormData();
var index = [];
variables[type] = null;
// On récupère la valeur de chaque propriété de "variables"
for (var variable in variables.data) {
index.push(variables.data[variable]);
}
// Tableau des valeurs de clés
const keys = Object.getOwnPropertyNames(variables.data);
var json_str = {};
for (let i = 0; i < keys.length; i++) {
json_str[keys[i]] = index[i];
}
json_str["options"] = {isnew: true};
// alert(JSON.stringify(json_str));
body.append(
"operations",
JSON.stringify(json_str)
);
body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
body.append("1", fichier);
for (var value of body.values()) {
alert(value);
}
const storage = await browser.storage.local.get("refresh_token");
const headers = {};
if (storage.refresh_token) {
headers.authorization = "JWT " + storage.refresh_token;
}
const res = await fetch(url_api + "/elements/", {
method: "POST",
headers: headers,
body: body,
});
return await res.json();
But if my element is well sent, it is empty. No title, no description, no image. It seems that body value isn't right. So my Api request is just "url_api/elements/", which just create an empty basic element.