Skip to content

Support two-way serialization/deserialization #909

Closed

Description

@stephenh

🤷 Motivation

We have types like JS Date or an internal LocalDate (only calendar dates, no times) that we want to encode/decode to JSON (or a string, like in a query string).

Libraries like Zod/Arktype/etc generally support deserialization, i.e. here's an unknown blob object literal, parse/safeParse it into my structure, and also transform the dueDate: "2024-01-01" key into --> dueDate: new LocalDate(...) during the process (zod transformers).

But they don't have serialization, which is if I have an object { dueDate: someJsDate }, and I want to serialize it, I want it to come out as dueDate: "2024-01-01" and not dueDate: Date.toString() or Date.toJSON() which is some really long ISO string.

Ideally I want to have a two-way codec, that for a given key, can do both custom serialization & deserialization.

Why should we prioritize solving it?

Because you're a new market entrant and hopefully will see this as an edge/feature to help drive your adoption. :-) 🤞

💡 Solution

How do you think we should solve the problem?

Ideally with something similar to Zod's transformers, but more of a "codec" or "serde" that does both serialization & deserialization.

This would mean new high-level methods like serialize or format (opposite of parse).

Why do you think this is the best solution?

This sort of approach keeps the schema in control of both serialization & deserialization, instead of being at the whims of whatever .toString / .toJSON behavior the values happen to use.

Did you consider any alternatives?

I've been looking for a runtime type library (Zod, see this comment, others) and the only one that does codecs/serde afaict is io-ts, which comes with too much baggage.

Honestly I understand if you consider this out-of-scope, but I'm just really surprised that so far basically all of the runtime type libraries have somewhat myopically focused on "only parse" and forgotten the other half of serde.

Activity

  1. ssalbdivad commented on Feb 17, 2024

    @ssalbdivad
    Member

    This is a really interesting topic and one I've thought a lot about but am still not quite sure of my stance on.

    When I was initially implementing morphs, I considered many solutions including a unique input/output that could be associated with a type. Especially working in the type system, I eventually determined that fundamentally, there was nothing special about input/output or serialize/deserialize compared to any other arbitrarily named transformations you might create for a type. Essentially, if you think about your types as a graph, really what you're defining is new edges (morphs) from the your vertex (type) to some other type (in this case string).

    I do think this is a very powerful concept (I created an empty issue a long time ago to follow up #574), but it seems to me bidirectional codecs are more an application of this larger morph-based graph than inherently useful in and of themselves, and in fact I've seen a lot of questions about why in @effect/schema codecs must always be bidirectional when often it doesn't reflect a valid transformation in one direction, so you end up creating an implementation that just throws which feels very clunky to me.

    That said, if you haven't seen https://github.com/Effect-TS/schema already it's a great library and might be just what you're looking for!

    If you're interested in fleshing out some of what I described re: morphs I'd definitely be interested in working together to tackle that, especially after the 2.0 release.

  2. moved this from To do to Backlog in arktypeioon Feb 17, 2024
  3. stephenh commented on Apr 7, 2024

    @stephenh
    Author

    Hello! Apologies from the really long delay in replying; your response made a lot of sense, but I was like "ah wow, 'graph of types'?! I'm going to really need to think about my reply...", and then well, finally got a chance to think/play with it today. :-)

    there was nothing special about input/output or serialize/deserialize compared
    to any other arbitrarily named transformations you might create for a type.

    I can see this being true...

    if you think about your types as a graph, really what you're defining is new edges
    (morphs) from the your vertex (type) to some other type (in this case string)

    I think I see what you mean; I hadn't actually tried morphs yet, so just now sketched out a "User type to JSON, JSON back to User type" prototype here:

    https://github.com/stephenh/typescript-sandbox/blob/arktype/src/arktype.test.ts#L6

    And, yeah, it looks like it works if I treat each "version of type" (User-as-json and User-as-pojo) as its own thing.

    Which makes sense, that for Arktype's current API there is only ever "input type --> output type", so to go the other way around, it makes sense to just flip the "output type --> input type".

    I think what's less than ideal, at least for this very specific use-case (storing a POJO as JSON, i.e. storing POJOs into jsonb columns), is the duplication in defining User twice.

    Is there a way to avoid that? Ideally I'd like to just define the User on its own, and have that definition know how to do In -> Out as well as Out -> In...

    Which, per your link:

    https://github.com/Effect-TS/schema

    Oh nice! I knew of Effect, but have historically shied away from it b/c of naively assuming it would to too-monad-y; I wrote Scala for ~3-4 years and really enjoyed it, but personally more so from the "better Java" angle than the "getting Haskell on the JVM" angle. :-)

    But they definitely have the type + encode + decode setup that I'm looking for, so I'll take a look!

    If you're interested in fleshing out some of what I described

    I'm definitely happy to chat over use cases and potential APIs!

    At first I was assuming that supporting the codec pattern (being able to call encode) would be a pretty large/breaking change to the Arktype API, because right now when I do userAsPojo(...json...) it didn't seem clear "if that's (implicitly) decode, where would the encode method even go?"

    But maybe something like:

    const userDecoded = user.decode(json);
    const userEncoded = user.encode(userDecoded);

    Would work, and user(...) stays as the common-case API/syntax-sugar for decoding.

    Granted, morphs would need to learn to (optionally--maybe by default the encodeFn is just value?.toJSON()) be two-way (accept an encodeFn), maybe something like:

    const user = type({
      firstName: "string",
      birthday: [LocalDate, "|>", decodeFn, encodeFn],
    });

    I know I flipped the order of "|>" there (I put LocalDate first instead of string)...

    At first that was an unintentional mistake, but actually I like it b/c imo it better communicates the "User.birthday is going to be a LocalDate" intent, and pushes the "here's how its encoded/decoded" to later in the tuple (maybe "two-way morphs" / codecs would have a different operator than |> ... <|> maybe?).

    Vs. the current API of birthday: ["string", ...] almost makes it sound like birthday: string is what User.birthday will be typed as, until you see/realize that the decodeFn tuple argument swaps it over to LocalDate.

    Anyway, that's my...mumble...months later thoughts! Thanks!

  4. ssalbdivad commented on Apr 11, 2024

    @ssalbdivad
    Member

    My intuition is that I'd rather have some way to define a group of "variants" of a type along with a syntax that allows you to conveniently transform between them, but I suppose that API could be defined in such a way that encode and decode could be defined and used in a way similar to what you describe.

    I definitely want to revisit this after the next release once the core type system is stable.

  5. robyoder commented on Feb 5, 2025

    @robyoder

    👋 A teammate linked me to this. Just wanted to add a vote and some context.

    We've used io-ts for years but most devs aren't familiar/comfortable with FP patterns and structures (Either et al) so we've built helper functions around it to make the codecs easier to use. Defining codecs is also somewhat annoying, though, especially how optional fields need to be represented as an intersection between a type and a partial type.

    All this to say, we've had conversations internally about moving to something else with a friendlier API, but I'm going to be really sad to lose bidirectional codecs. For example, we have some data structures that have to be transformed from base64url to bytes to JSON string to object, and then back again when encoding. We can make separate functions for these, but that really breaks composability. Now any type that uses one of these transforms (or includes a type that uses, etc. recursively) would have to have a twin type that goes the other direction.

    We could pair these twin types with our own data structure, but it's the fact that the type has to be defined twice and kept in sync that's the real annoyance and opportunity for divergence.

    I share Stephen's sentiment of frustration that only deeply functional libraries seem to care about this kind of composability.

  6. gabrielgrant commented on Feb 13, 2025

    @gabrielgrant
    Contributor

    This might be naive, but could the duplication not be avoided by extracting the base type definition from the type() calls?

    So (from your linked example) instead of

    const userAsPojo = type({
      firstName: "string",
      // decode the string to a LocalDate
      birthday: ["string", "|>", (s) => new LocalDate(s)],
    });
    
    // Revert the user, go from POJO to JSON
    const userAsJson = type({
      firstName: "string",
      // encode the LocalDate to a string
      birthday: [
        { month: "number", year: "number", day: "number" },
        "|>",
        (date) => date.year + "-" + date.month + "-" + date.day,
      ],
    });
    

    do

    const baseUserDef = {
      firstName: "string",
    }
    
    const userAsPojo = type({
      ...baseUserDef,
      // decode the string to a LocalDate
      birthday: ["string", "|>", (s) => new LocalDate(s)],
    });
    
    // Revert the user, go from POJO to JSON
    const userAsJson = type({
      ...baseUserDef,
      // encode the LocalDate to a string
      birthday: [
        { month: "number", year: "number", day: "number" },
        "|>",
        (date) => date.year + "-" + date.month + "-" + date.day,
      ],
    });
    

    Obviously more useful if there are more shared fields

    Assuming the encoding/decoding just happens at the edge of the application, whereas the POJO version is used throughout, I might be inclined to consider that the "canonical" type, with the conversions being variants. But I think the same basic pattern would work, right?

    Thinking something like this (which also adds validation to the actual date string. In this particular case might be better done using builtin JS date logic. And if you didn't want to make LocalDate a ArkType type, I think it could just be replaced with instanceOf):

    
    const LocalDate = type({
      month: "1 <= number.integer <= 12",
      year: "number.integer",
      day: "1 <= number.integer <= 31",
    });
    
    const LocalDateFromString = type("string").pipe.try(dateStr: string => {
      const [year, month, day] = date.split("-");
      return {
        year: parseInt(year),
        month: parseInt(month),
        day: parseInt(day)
      }
    });
    
    const baseUserDef = {
      firstName: "string",
      birthday: LocalDate
    }
    
    const userFromJson = type({
      ...baseUserDef,
      birthday: LocalDateFromString,
    });
    
    // Revert the user, go from POJO to JSON
    const userAsJson = type({
      ...baseUserDef,
      // encode the LocalDate to a string
      // this could also be broken out as a separate type if desired
      birthday: [
        LocalDate,
        "|>",
        (date) => date.year + "-" + date.month + "-" + date.day,
      ],
    });
    
    

    Note haven't actually tested this, so likely has some errors

  7. frolic commented on Mar 9, 2025

    @frolic
    Contributor

    I have a codec pattern inside another project I am working on:
    https://github.com/frolic/typed-http/blob/main/src/arktype/codec.test.ts

    Let me know if it would be useful to lift this out into its own package and I will!

  8. stephenh commented on Mar 10, 2025

    @stephenh
    Author

    @frolic I scanned your codec tests & (more briefly) the impl--it looks great, and exactly what I'm looking for! Would be great to have it packaged as its own thing or even better worked into arktype itself. 🎉

    Thanks for linking to it!

  9. ssalbdivad commented on Mar 10, 2025

    @ssalbdivad
    Member

    Would love to see this published so I have something to point people to.

    I mentioned to @frolic it's probably best we not build it in to ArkType yet because of the graph-based approach I mentioned previously being the long term vision for the internal API that would solve this.

    Likely, the end result would be some sugar over that so it ended up looking very similar to @frolic's API, but would want to avoid committing to that internally until we nail down what n-vertices solution would look like.

  10. stephenh commented on Mar 11, 2025

    @stephenh
    Author

    @ssalbdivad just curious, but what do you mean by an n-vertices solution?

    I get you're saying (using the example from @frolic 's test cases) "bigint is a vertex/node in the type graph", "string is a vertex/node in the type graph", and besides just "two-way edges between bigint and string", we might have a 3rd vertex/node come into play? Do you have an example, just to wrap my head around?

    Also @frolic this might be a lazy ask, but I didn't see it in the test cases--does your codec library support reusing/composing the codecs, i.e. our use case is storing jsonb columns in postgres:

    • we want to have a Temporal.PlainDate of birthday in our POJO
    • we'd like to define a codec for PlainDate <=> string to store in a jsonb column
    • besides just storing LocalDates directly, we'd like to define a codec for an Author POJO that has several fields, one of which is a birthday: Temporal.PlainDate, that reuses the plainDateCodec for its serde

    I think this is a very standard/vanilla use case, so is probably something you already support / had in mind while building your codec library?

    Thanks!

  11. frolic commented on Mar 11, 2025

    @frolic
    Contributor

    Yep! I think this might be hidden inside some other parts of this library, but I'll be sure to expose that if I pull this into a codec lib. The idea is that codecs become part of your type scope so you can compose them however you need.

  12. ssalbdivad commented on Mar 11, 2025

    @ssalbdivad
    Member

    @stephenh I haven't figured out the API for representing it but essentially, instead of thinking of it as relationships between arbitrary types, thing of a group of representations of the same entity.

    Maybe you have one type representing a JSON string for the server, the object it is parsed to, and an alternate variant for the database with an id field added.

    Bidirectional encoding is a special case of this sort of graph.

  13. DrJume commented on Feb 27, 2026

    @DrJume

    This would also enable usage of Date() with a schema that can be transformed to a JSON Schema (using a bidirectional Date↔string (iso datetime) transformation).
    Just like with Zod Codecs 👍

  14. added a commit that references this issue on Oct 19, 2026
  15. ssalbdivad commented on Nov 18, 2026

    @ssalbdivad
    Member

    Fixed in 3.0.0-beta.0 (#1728). Try it with npm i arktype@next.

  16. moved this from Backlog to Done (merged or closed) in arktypeioon Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Done (merged or closed)

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions