mirror of
https://github.com/ahmadk953/tasko.git
synced 2025-02-07 03:32:51 +00:00
29 lines
728 B
TypeScript
29 lines
728 B
TypeScript
|
import { z } from "zod";
|
||
|
|
||
|
export type FieldErrors<T> = {
|
||
|
[K in keyof T]?: string[];
|
||
|
};
|
||
|
|
||
|
export type ActionState<TInput, TOutput> = {
|
||
|
fieldErrors?: FieldErrors<TInput>;
|
||
|
error?: string | null;
|
||
|
data?: TOutput;
|
||
|
};
|
||
|
|
||
|
export const createSafeAction = <TInput, TOutput>(
|
||
|
schema: z.Schema<TInput>,
|
||
|
handler: (validatedData: TInput) => Promise<ActionState<TInput, TOutput>>
|
||
|
) => {
|
||
|
return async (data: TInput): Promise<ActionState<TInput, TOutput>> => {
|
||
|
const validationResult = schema.safeParse(data);
|
||
|
if (!validationResult.success) {
|
||
|
return {
|
||
|
fieldErrors: validationResult.error.flatten()
|
||
|
.fieldErrors as FieldErrors<TInput>,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
return handler(validationResult.data);
|
||
|
};
|
||
|
};
|