All files / src/features/milestones/api milestones.schemas.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52        9x     9x                       9x               158x               16x 1x 15x 2x                 9x        
import { z } from 'zod'
 
import { todayDateString } from '@/lib/date'
 
export const milestoneCategorySchema = z.enum(['MOTOR', 'LANGUAGE', 'SOCIAL', 'COGNITIVE', 'OTHER'])
export type MilestoneCategory = z.infer<typeof milestoneCategorySchema>
 
export const milestoneSchema = z.object({
  id: z.string().uuid(),
  babyId: z.string().uuid(),
  title: z.string(),
  description: z.string().nullable(),
  achievedAt: z.string(),
  category: milestoneCategorySchema,
  photoUrl: z.string().nullable(),
  createdAt: z.string(),
})
export type Milestone = z.infer<typeof milestoneSchema>
 
export const milestoneListSchema = z.array(milestoneSchema)
 
/**
 * `achievedAt` can't be validated by a static schema alone — it depends on
 * the selected baby's birthDate — so the schema is built per-baby via this
 * factory instead of being a module-level constant.
 */
export function createMilestoneFormSchema(birthDate: string) {
  return z.object({
    title: z.string().trim().min(1),
    description: z.string().optional(),
    achievedAt: z
      .string()
      .min(1)
      .date()
      .superRefine((value, ctx) => {
        if (value > todayDateString()) {
          ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'milestones.form.achievedAtFuture' })
        } else if (value < birthDate) {
          ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'milestones.form.achievedAtBeforeBirth' })
        }
      }),
    category: milestoneCategorySchema,
    photoUrl: z.union([z.string().url(), z.literal('')]).optional(),
  })
}
export type MilestoneFormInput = z.infer<ReturnType<typeof createMilestoneFormSchema>>
 
export const milestonePhotoUploadResponseSchema = z.object({
  url: z.string().url(),
})
export type MilestonePhotoUploadResponse = z.infer<typeof milestonePhotoUploadResponseSchema>