mirror of
https://github.com/ahmadk953/tasko.git
synced 2025-05-04 04:33:10 +00:00
Initial Commit
This commit is contained in:
commit
f3e2f01bd7
150 changed files with 13612 additions and 0 deletions
28
lib/create-safe-action.ts
Normal file
28
lib/create-safe-action.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
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);
|
||||
};
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue