5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-07 00:51:49 +08:00
wails/v3/internal/runtime/desktop/calls.js

107 lines
2.5 KiB
JavaScript

/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
/* jshint esversion: 9 */
import {newRuntimeCallerWithID, objectNames} from "./runtime";
import { nanoid } from 'nanoid/non-secure';
let call = newRuntimeCallerWithID(objectNames.Call);
let CallBinding = 0;
let callResponses = new Map();
function generateID() {
let result;
do {
result = nanoid();
} while (callResponses.has(result));
return result;
}
export function callCallback(id, data, isJSON) {
let p = callResponses.get(id);
if (p) {
if (isJSON) {
p.resolve(JSON.parse(data));
} else {
p.resolve(data);
}
callResponses.delete(id);
}
}
export function callErrorCallback(id, message) {
let p = callResponses.get(id);
if (p) {
p.reject(message);
callResponses.delete(id);
}
}
function callBinding(type, options) {
return new Promise((resolve, reject) => {
let id = generateID();
options = options || {};
options["call-id"] = id;
callResponses.set(id, {resolve, reject});
call(type, options).catch((error) => {
reject(error);
callResponses.delete(id);
});
});
}
export function Call(options) {
return callBinding(CallBinding, options);
}
export function CallByName(name, ...args) {
// Ensure first argument is a string and has 2 dots
if (typeof name !== "string" || name.split(".").length !== 3) {
throw new Error("CallByName requires a string in the format 'package.struct.method'");
}
// Split inputs
let parts = name.split(".");
return callBinding(CallBinding, {
packageName: parts[0],
structName: parts[1],
methodName: parts[2],
args: args,
});
}
export function CallByID(methodID, ...args) {
return callBinding(CallBinding, {
methodID: methodID,
args: args,
});
}
/**
* Call a plugin method
* @param {string} pluginName - name of the plugin
* @param {string} methodName - name of the method
* @param {...any} args - arguments to pass to the method
* @returns {Promise<any>} - promise that resolves with the result
*/
export function Plugin(pluginName, methodName, ...args) {
return callBinding(CallBinding, {
packageName: "wails-plugins",
structName: pluginName,
methodName: methodName,
args: args,
});
}