One line API call from Javascript
This will pass a method name and a list of arguments to a web-url, passing the classname of the calling javascript. My intent is to allow this to call a same-named class on the server, regardless of the remote language. I've made a working version with PHP, but it was crumb, so I... don't really know where that code is right now.
This also depends on JS Autowire... uhh. Actually, I don't think it really does, but... that's how I wrote it?.
Needless to say, this post needs many improvements. I have a more robust version I'm sorta working on, and I think I'll update this when it's done.
To make it a one-liner, you'd have to do result = await fancyServerObject.fetch(method, ...args);
class FancyServer extends RB.Autowire {
__attach(){
this.func = function(){
alert('with timeout');
}
}
showSpinnerWheelDelayed(ms){
setTimeout(this.func,ms);
}
cancelSpinnerWheel(){
clearTimeout(this.func);
}
async fetch(method,...args){
const uploadMethod = "POST";
const url = '/call_api/';
const params = {
"method": method,
"class":this.class ?? this.constructor.name
};
for (const index in args){
params[index] = args[index];
}
// console.log(args);
// console.log(params);
var formData = new FormData();
for(var key in params){
const param = params[key];
if (param!=null
&&typeof param == typeof []){
for(const val of param){
formData.append(key,val);
}
} else formData.append(key,params[key]);
}
const submitData = {method: uploadMethod, mode: "cors"};
if (uploadMethod=='POST')submitData['body'] = formData;
const res = await fetch(url, submitData);
const json = await res.json();
console.log(json);
return json.methods[method];
}
}