Effect CommunityEC
Effect Community17mo ago
3 replies
Bennie

Transforming ISO Date String to EventDate with Schema Mapping

Is there a way to map a brand/schema constructor? What I'm trying to do is have a transform go from an ISO date string to a Date and then create a Brand named EventDate. That all works well, but when I use the make function to create a new EventDate from a Date, I can't figure out how to strip the time portion off as part of the Schema. What I have so far:

/**
 * An Effect Schema representation of an {@link EventDate}.
 */
export const EventDate = Schema.transform(
  Schema.String.pipe(
    Schema.nonEmptyString({ message: () => "Cannot be empty." }),
    Schema.pattern(
      /^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,
      { message: () => "Date must be in the pattern of yyyy-MM-dd" },
    ),
  ),
  Schema.typeSchema(Schema.Date),
  {
    strict: true,
    decode: (str: string) => parseISO(str),
    encode: (date: Date) => format(date, "yyyy-MM-dd"),
  },
).pipe(Schema.brand("EventDate"));

/**
 * The date of the training event.
 */
export type EventDate = Schema.Schema.Type<typeof EventDate>;
Was this page helpful?