yup-server-action
Version:
Server actions powered by Yup
41 lines (37 loc) • 2.06 kB
TypeScript
import * as yup from 'yup';
type MaybePromise<T> = T | Promise<T>;
type NoInput = undefined;
type ServerActionHandlerContext<TInput> = TInput extends NoInput ? {} : {
input: TInput;
};
type ServerActionHandler<TInput, TResult> = (ctx: ServerActionHandlerContext<TInput>) => MaybePromise<TResult>;
type ServerAction<TInput, TResult = any> = {
_inputType: TInput;
_resultType: TResult;
run: (rawInput: TInput extends undefined ? void : TInput) => Promise<TResult>;
};
type ServerActionBuilderWithoutInput = {
input<TNewInputSchema extends yup.ObjectSchema<Record<string, unknown>>>(schema: TNewInputSchema): ServerActionBuilderWithInput<yup.InferType<TNewInputSchema>>;
handle<TResult>(fn: ServerActionHandler<NoInput, TResult>): ServerAction<undefined, TResult>;
};
type ServerActionBuilderWithInput<TInput> = {
handle<TResult>(fn: ServerActionHandler<TInput, TResult>): ServerAction<TInput, TResult>;
};
declare function createServerAction(): ServerActionBuilderWithoutInput;
declare function createServerAction<TSchema extends yup.ObjectSchema<Record<string, unknown>>>(schema: TSchema): ServerActionBuilderWithInput<yup.InferType<TSchema>>;
type InferInput<T> = T extends ServerAction<infer Input, any> ? Input : never;
type InferResult<T> = T extends ServerAction<any, infer Result> ? Result : never;
type UseServerActionOptions<TAction extends ServerAction<any, any>> = {
onSuccess?: (data: InferResult<TAction>) => void;
onError?: (error: unknown) => void;
};
type UseServerActionReturn<TAction extends ServerAction<any, any>> = {
execute: InferInput<TAction> extends undefined ? () => Promise<void> : (input: InferInput<TAction>) => Promise<void>;
isPending: boolean;
isSuccess: boolean;
isError: boolean;
data: InferResult<TAction> | undefined;
error: unknown | undefined;
};
declare function useServerAction<TAction extends ServerAction<any, any>>(action: TAction, options?: UseServerActionOptions<TAction>): UseServerActionReturn<TAction>;
export { createServerAction, useServerAction };