UNPKG

slightning-coco-widget

Version:

SLIGHTNING 的 CoCo 控件框架。

61 lines (60 loc) 2.71 kB
import { FunctionType } from "../type"; import { traverseTypes } from "./utils"; export function addTransformMethodsThrows(types, widget) { traverseTypes(types, { MethodTypes(node) { if (node.value.throws == null || node.value.throws.isVoid()) { return; } const transformedMethod = Object.assign(Object.assign({}, node.value), { key: `__slightning_coco_widget_transformed_throws__${node.value.key}`, block: [...node.value.block], returns: null, throws: null }); const successIndex = transformedMethod.block.filter((part) => typeof part == "object").length; transformedMethod.block.push("成功则", { key: "__slightning_coco_widget_success_callback__", label: "成功回调", type: new FunctionType({ block: node.value.returns == null || node.value.returns.isVoid() ? [] : [{ key: "value", label: "值", type: node.value.returns }] }) }); const errorIndex = transformedMethod.block.filter((part) => typeof part == "object").length; transformedMethod.block.push("失败则", { key: "__slightning_coco_widget_error_callback__", label: "失败回调", type: new FunctionType({ block: [{ key: "error", label: "错误", type: node.value.throws }] }) }); node.insertAfter(transformedMethod); Object.defineProperty(widget.prototype, transformedMethod.key, { value: function (...args) { const errorCallback = args.splice(errorIndex, 1)[0]; const successCallback = args.splice(successIndex, 1)[0]; try { const result = this[node.value.key].apply(this, args); if (result instanceof Promise) { result.then(successCallback); result.catch(errorCallback); } else { successCallback(result); } } catch (error) { errorCallback(error); } }, writable: true, enumerable: false, configurable: true }); } }); return [types, widget]; }