From c7d4dadbbb3457aa8571c1f312928ce6a9aef63f Mon Sep 17 00:00:00 2001 From: Evandro Fonseca Junior Date: Sun, 26 Oct 2025 23:11:21 -0300 Subject: [PATCH] refactor(validation): refactor createDonationSchema to use discriminatedUnion Refactored the createDonationSchema from a combination of .object().and(z.union()) to a discriminatedUnion based on the "anonymous" field. This improves type safety and validation logic by explicitly handling anonymous and identified donations, ensuring customAmount is properly validated in both cases. The change maintains the same validation rules while simplifying the schema structure. --- lib/validation-schemas.ts | 41 ++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/lib/validation-schemas.ts b/lib/validation-schemas.ts index a9eac6d..5792821 100644 --- a/lib/validation-schemas.ts +++ b/lib/validation-schemas.ts @@ -80,28 +80,25 @@ export const customAmountSchema = z // Schema completo para criação de doação export const createDonationSchema = z - .object({ - tier: donationTierSchema, - anonymous: z.boolean().optional().default(false), - customAmount: z.number().optional(), - }) - .and( - z.union([ - // Doação anônima - não precisa de dados pessoais - z.object({ - anonymous: z.literal(true), - }), - // Doação identificada - precisa de todos os dados - z.object({ - anonymous: z.literal(false), - donorName: nameSchema, - donorEmail: emailSchema, - donorPhone: phoneSchema, - donorTaxId: documentSchema, - donorMessage: messageSchema, - }), - ]) - ) + .discriminatedUnion("anonymous", [ + // Doação anônima + z.object({ + tier: donationTierSchema, + anonymous: z.literal(true), + customAmount: z.number().optional(), + }), + // Doação identificada + z.object({ + tier: donationTierSchema, + anonymous: z.literal(false), + donorName: nameSchema, + donorEmail: emailSchema, + donorPhone: phoneSchema, + donorTaxId: documentSchema, + donorMessage: messageSchema, + customAmount: z.number().optional(), + }), + ]) .refine( (data) => { // Se tier for custom, customAmount é obrigatório