Effect CommunityEC
Effect Community3y ago
13 replies
bste

Converting Code from Zod to Effect/Schema: Equivalent of `z.transform()` Function

Hey all 👋🏻
I'm trying to convert some code from zod to effect/schema. I'm stuck on an equivalent of the z.transform() function. Basically I've got a string field that I'd like to convert to a luxon DateTime that I've been doing with
z.string().transform(date => DateTime.fromISO(date, { zone: "Pacific/Auckland" }))
I've had to specify the tz manually as the source doesn't use a proper date time string.
I'm a bit lost as to how I should do this as I can't figure out how to declare a Schema<string, DateTime>. I've faffed around and come up with this, but it feels like a lot to just do what was a one liner transformation

const isDateTime = (o: unknown): o is DateTime => o instanceof DateTime
const dateTimeFromSelf: S.Schema<DateTime> = S.declare(
  [],
  S.struct({}),
  () => (o, _, ast) => !isDateTime(o)
    ? ParseResult.failure(ParseResult.type(ast, o))
    : ParseResult.success(o),
  {
    [AST.IdentifierAnnotationId]: "DateTime"
  }
)

const dateTimeFromString = (): S.Schema<string, DateTime> =>
  S.transformOrFail(
    S.string,
    dateTimeFromSelf,
    (s, _, ast) => {
      try {
        return ParseResult.success(DateTime.fromISO(s, { zone: "Pacific/Auckland" }))
      } catch (e) {
        return ParseResult.failure(ParseResult.type(ast, s))
      }
    },
    dateTime => ParseResult.success(dateTime.toISODate())
  )


is there a better way?
Was this page helpful?