x-control-panel/web-ui/vue-app/src/api/RpcClientBase.ts

35 lines
973 B
TypeScript

export class RpcClientBase {
constructor(private baseUrl: string) {
}
public async callModuleMethod<T>(module: string, methodName: string, params?: any):Promise<T> {
return this.call(module + "." + methodName, params);
}
protected async call<T>(method: string, params?: any): Promise<T> {
const response = await fetch(this.baseUrl, {
method: 'POST',
credentials: "include",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
jsonrpc: '2.0',
method,
params,
id: Date.now()
})
});
if (!response.ok) {
throw new Error(`RPC call ${method} failed: ${response.statusText}`);
}
const data = await response.json();
if (data.error) {
throw new Error(`RPC error: ${data.error.message}`);
}
return data.result;
}
}