Untitled
unknown
javascript
a year ago
1.5 kB
16
Indexable
export async function createFragment(user, content, type) {
console.log('Creating fragment with content:', content, 'and type:', type);
let body;
// Ensure the content is always treated as binary data
if (content instanceof Uint8Array || content instanceof ArrayBuffer) {
body = new Blob([content], { type });
} else if (typeof content === 'string') {
const encoder = new TextEncoder();
body = new Blob([encoder.encode(content)], { type });
} else {
const jsonString = JSON.stringify(content);
const encoder = new TextEncoder();
body = new Blob([encoder.encode(jsonString)], { type: 'application/json' });
type = 'application/json'; // Ensure the type matches the content
}
console.log('Content-Type:', type);
console.log('Content-Length:', body.size);
// Only set Content-Type for JSON; for binary data, let the browser set it
const headers = {
...user.authorizationHeaders(),
};
if (type === 'application/json') {
headers['Content-Type'] = type;
}
const response = await fetch(`${apiUrl}/v1/fragments`, {
method: 'POST',
headers: headers,
body: body, // Send the Blob directly, allowing the browser to handle Content-Type correctly
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Error creating fragment: ${response.statusText} - ${errorText}`);
}
const data = await response.json();
console.log('Fragment created successfully:', data);
return data;
}Editor is loading...
Leave a Comment