Effect CommunityEC
Effect Community3y ago
8 replies
attila

Using io-ts to Create Codecs for Transforming Buffers to ULIDs

With io-ts, I used to be able to create a codec that transforms a Buffer to a ULID and vice versa by saying:
import { pipe } from "fp-ts/lib/function";
import * as id128 from "id128";
import * as codec from "io-ts/lib/Codec";
import * as decoder from "io-ts/lib/Decoder";
import { buffer } from "./buffer"; // assume the implementation of a codec.Codec<unknown, Buffer, Buffer>
import { ULID } from "./ulid"; // assume the implementation of a codec.Codec<unknown, string, ULID> for a brand ULID type

export const UlidFromBuffer: codec.Codec<unknown, Buffer, ULID> = codec.make(
  pipe(
    buffer,
    decoder.parse((a) => {
      try {
        return decoder.success(id128.Ulid.construct(a).toCanonical());
      } catch (e) {
        return decoder.failure(a, "a ULID buffer");
      }
    }),
    decoder.compose(ULID)
  ),
  { encode: (a) => Buffer.from(id128.Ulid.fromCanonical(a).bytes) }
);


Is it somehow possible to replicate this using today's schema library? If not, is the lack of this ability intended?
Was this page helpful?