@kellanjs/actioncraft
Version:
Fluent, type-safe builder for Next.js server actions.
44 lines • 1.6 kB
JavaScript
import { ActionCraftError } from "./error.js";
export function unwrap(resultOrPromise) {
// Handle Promise case
if (resultOrPromise instanceof Promise) {
return resultOrPromise.then((result) => _unwrapSync(result));
}
// Handle direct result case
return _unwrapSync(resultOrPromise);
}
/**
* Synchronously unwraps a result, throwing on error.
*/
function _unwrapSync(result) {
// Handle api-style results ({ success: true/false })
if (typeof result === "object" && result !== null && "success" in result) {
const apiResult = result;
if (apiResult.success) {
return apiResult.data;
}
throw new ActionCraftError(apiResult.error);
}
// Handle functional-style results ({ type: "ok"/"err" })
if (typeof result === "object" && result !== null && "type" in result) {
const functionalResult = result;
if (functionalResult.type === "ok") {
return functionalResult.value;
}
throw new ActionCraftError(functionalResult.error);
}
throw new Error("Invalid result format from ActionCraft action");
}
/**
* Creates a throwable version of an ActionCraft action.
* The returned function throws on error instead of returning Result objects.
*/
export function throwable(action) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (async (...args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await action(...args);
return unwrap(result);
});
}
//# sourceMappingURL=utils.js.map