yup-server-action
Version:
Server actions powered by Yup
92 lines (89 loc) • 2.77 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
createServerAction: () => createServerAction,
useServerAction: () => useServerAction
});
module.exports = __toCommonJS(src_exports);
// src/create-server-action.ts
function internalBuilder(inputSchema) {
const obj = {
input(schema) {
return internalBuilder(schema);
},
handle(fn) {
return {
_inputType: void 0,
_resultType: void 0,
run: async (rawInput) => {
const parsedInput = inputSchema ? await inputSchema.validate(rawInput, { abortEarly: false }) : void 0;
const ctx = inputSchema ? { input: parsedInput } : {};
return fn(ctx);
}
};
}
};
return obj;
}
function createServerAction(schema) {
return schema ? internalBuilder(schema) : internalBuilder();
}
// src/use-server-action.ts
var import_react = require("react");
function useServerAction(action, options) {
const [isPending, setIsPending] = (0, import_react.useState)(false);
const [isSuccess, setIsSuccess] = (0, import_react.useState)(false);
const [isError, setIsError] = (0, import_react.useState)(false);
const [data, setData] = (0, import_react.useState)(void 0);
const [error, setError] = (0, import_react.useState)(void 0);
const execute = async (...args) => {
setIsPending(true);
setIsSuccess(false);
setIsError(false);
try {
const result = await action.run(...args);
options?.onSuccess?.(result);
setIsSuccess(true);
setData(result);
} catch (error2) {
options?.onError?.(error2);
setIsError(true);
setError(error2);
throw error2;
} finally {
setIsPending(false);
}
};
return {
execute,
isPending,
isSuccess,
isError,
data,
error
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createServerAction,
useServerAction
});
//# sourceMappingURL=index.js.map