Use the fetch API in Puter.js's Convert module

This commit is contained in:
jelveh
2025-02-06 19:45:10 -08:00
parent 1e5deabcdb
commit d4b4df06fd
+37 -6
View File
@@ -1,10 +1,8 @@
import * as utils from '../lib/utils.js';
class Convert {
constructor(context) {
this.authToken = context.authToken;
this.APIOrigin = context.APIOrigin;
this.appID = context.appID; // Might not be strictly necessary for this module, but good for consistency
this.appID = context.appID;
}
setAuthToken(authToken) {
@@ -15,11 +13,10 @@ class Convert {
this.APIOrigin = APIOrigin;
}
convert = async (...args) => {
let options = {};
// if args is a single object, assume it is the options object
// If args is a single object, assume it is the options object
if (typeof args[0] === 'object' && args[0] !== null) {
options = args[0];
} else {
@@ -32,7 +29,41 @@ class Convert {
};
}
return utils.make_driver_method(['source', 'to'], 'convert-files', undefined, 'convert').call(this, options);
try {
const response = await fetch(`${this.APIOrigin}/drivers/call`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.authToken}`
},
body: JSON.stringify({
interface: 'convert-files',
method: 'convert',
args: {
source: options.source,
to: options.to
}
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Conversion failed');
}
if (options.success && typeof options.success === 'function') {
options.success(data);
}
return data;
} catch (error) {
if (options.error && typeof options.error === 'function') {
options.error(error);
}
throw error;
}
}
}