53 lines
1.1 KiB
JavaScript
53 lines
1.1 KiB
JavaScript
|
|
export class RPCError extends Error {
|
|
|
|
constructor(source) {
|
|
|
|
super("A remote error occured");
|
|
|
|
this.source = source;
|
|
this.name = this.constructor.name;
|
|
|
|
if (typeof Error.captureStackTrace === 'function') {
|
|
Error.captureStackTrace(this, this.constructor);
|
|
} else {
|
|
this.stack = (new Error(message)).stack;
|
|
}
|
|
|
|
}
|
|
|
|
getSource() {
|
|
return this.source;
|
|
}
|
|
|
|
}
|
|
|
|
export class JSONRPC {
|
|
|
|
constructor(endpoint) {
|
|
this.endpoint = endpoint;
|
|
this.id = 0;
|
|
}
|
|
|
|
call(method, params, isNotification = false) {
|
|
const requestId = this.id++;
|
|
return fetch(this.endpoint, {
|
|
method: 'POST',
|
|
headers:{
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
id: isNotification ? null : requestId,
|
|
method,
|
|
params: params || [],
|
|
})
|
|
})
|
|
.then(res => res.json())
|
|
.then(result => {
|
|
if (result.error) throw new RPCError(result.error);
|
|
if (!isNotification && requestId !== result.id) throw new Error("unexpected id in rpc response");
|
|
return result;
|
|
});
|
|
}
|
|
|
|
} |