minigame-std
Version:
Cross-platform standard library for WeChat minigame and web browsers with unified APIs for crypto, fs, fetch, storage, and more.
102 lines (101 loc) • 3.33 kB
JavaScript
import { Err, Ok, tryAsyncResult } from "happy-rusty";
import { Future } from "tiny-future";
import { miniGameFailureToError } from "./_internal.mjs";
//#region src/std/utils/resultify.ts
/**
* 将小游戏异步 API 转换为返回 `AsyncResult<T, E>` 的新函数,需要转换的 API 必须是接受可选 `success` 和 `fail` 回调的函数,并且其返回值必须是 `void` 或 `PromiseLike`。
*
* 其中 `T` 为 `success` 回调的参数类型,`E` 为 `fail` 回调的参数类型。
*
* @param api - 小游戏异步 API。
* @returns 返回一个新的函数,该函数返回 `AsyncResult<T, E>`。
* @since 2.0.0
* @example
* ```ts
* // 将 wx.setStorage 转换为 AsyncResult 风格
* const setStorageAsync = asyncResultify(wx.setStorage);
* const result = await setStorageAsync({ key: 'test', data: 'value' });
* if (result.isOk()) {
* console.log('存储成功');
* } else {
* console.error('存储失败:', result.unwrapErr());
* }
* ```
*/
function asyncResultify(api) {
return ((...args) => {
const future = new Future();
const options = args[0] ?? {};
const { success, fail } = options;
options.success = (res) => {
success?.(res);
future.resolve(Ok(res));
};
options.fail = (err) => {
fail?.(err);
future.resolve(Err(err));
};
const ret = api(options);
if (ret != null && typeof ret === "object" && typeof ret.then === "function") return tryAsyncResult(ret);
else if (ret !== void 0) {}
return future.promise;
});
}
/**
* `asyncResultify` 的变体,将小游戏异步 API 转换为返回 `AsyncIOResult<T>` 的新函数。
*
* 与 `asyncResultify` 不同的是,此函数会将 `fail` 回调的 `WechatMinigame.GeneralCallbackResult` 转换为 `Error` 类型。
*
* @param api - 小游戏异步 API。
* @returns 返回一个新的函数,该函数返回 `AsyncIOResult<T>`。
* @since 2.0.0
* @example
* ```ts
* // 将 wx.setStorage 转换为 AsyncIOResult 风格
* const setStorageAsync = asyncIOResultify(wx.setStorage);
* const result = await setStorageAsync({ key: 'test', data: 'value' });
* if (result.isOk()) {
* console.log('存储成功');
* } else {
* console.error('存储失败:', result.unwrapErr().message);
* }
* ```
*/
function asyncIOResultify(api) {
const wrapped = asyncResultify(api);
return (async (...args) => {
return (await wrapped(...args)).mapErr(miniGameFailureToError);
});
}
/**
* 将小游戏同步 API 转换为返回 `IOResult<T>` 的新函数。
*
* 功能类似于 `tryGeneralSyncOp`,但以函数包装的方式使用,将可能抛出的异常捕获并转换为 `IOResult`。
*
* @param api - 小游戏同步 API。
* @returns 返回一个新的函数,该函数返回 `IOResult<T>`。
* @since 2.0.0
* @example
* ```ts
* // 将 wx.getStorageSync 转换为 IOResult 风格
* const getStorageSync = syncIOResultify(wx.getStorageSync);
* const result = getStorageSync('test');
* if (result.isOk()) {
* console.log('获取成功:', result.unwrap());
* } else {
* console.error('获取失败:', result.unwrapErr().message);
* }
* ```
*/
function syncIOResultify(api) {
return (...args) => {
try {
return Ok(api(...args));
} catch (e) {
return Err(miniGameFailureToError(e));
}
};
}
//#endregion
export { asyncIOResultify, asyncResultify, syncIOResultify };
//# sourceMappingURL=utils.mjs.map