@simplito/privmx-webendpoint
Version:
PrivMX Web Endpoint library
66 lines (63 loc) • 1.95 kB
JavaScript
;
/*!
PrivMX Web Endpoint.
Copyright © 2024 Simplito sp. z o.o.
This file is part of the PrivMX Platform (https://privmx.dev).
This software is Licensed under the PrivMX Free License.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Api = void 0;
const IdGenerator_1 = require("./IdGenerator");
const NativeError_1 = require("./NativeError");
class Api {
lib;
promises;
taskIdGenerator;
constructor(lib) {
this.lib = lib;
this.taskIdGenerator = new IdGenerator_1.IdGenerator();
this.promises = new Map();
this.setResultsCallback();
}
async runAsync(func) {
return new Promise((resolve, reject) => {
const taskId = this.generateId();
this.promises.set(taskId, { resolve, reject });
func(taskId);
});
}
resolveResult(result) {
if (result.status == true) {
this.promises.get(result.taskId).resolve(result.result);
}
else {
this.promises.get(result.taskId).reject(this.toNativeError(result.error));
}
this.promises.delete(result.taskId);
}
generateId() {
return this.taskIdGenerator.generateId();
}
setResultsCallback() {
this.lib.setResultsCallback((result) => this.resolveResult(result));
}
toNativeError(error) {
if (this.isRawCppError(error)) {
return new NativeError_1.NativeError(error);
}
if (error instanceof Error) {
return error;
}
return new Error(typeof error === "string" ? error : JSON.stringify(error));
}
isRawCppError(obj) {
return (typeof obj === "object" &&
obj !== null &&
"code" in obj &&
"name" in obj &&
"scope" in obj);
}
}
exports.Api = Api;