Codecs
Create type-safe encoders and decoders with createCodec.
Creating a Codec
Use createCodec to create an encoder/decoder pair:
// Demonstrates: Creating and using codecs for encode/decode
import { RStruct, RString, RU32, field, createCodec } from "@grounds/schema";
import type { Static } from "@sinclair/typebox";
// Define a schema
const UserSchema = RStruct({
id: field(0, RU32()),
name: field(1, RString()),
});
type User = Static<typeof UserSchema>;
// Create a codec from the schema
const userCodec = createCodec(UserSchema);
// Create a user object
const user: User = { id: 42, name: "Bob" };
// Encode and decode using .andThen() chaining
userCodec
.encode(user)
.andThen((bytes) => {
console.log("Encoded:", bytes.length, "bytes");
console.log("Hex:", Buffer.from(bytes).toString("hex"));
return userCodec.decode(bytes);
})
.match(
(decoded) => {
console.log("Decoded:", decoded);
console.log("Roundtrip successful!");
},
(err) => {
console.error("Failed:", err.message);
},
);
Codec API
A codec provides two methods:
encode(value)
Encodes a value to bytes:
const result: Result<Uint8Array, EncodeError> = codec.encode(value);
decode(bytes)
Decodes bytes to a value:
const result: Result<T, DecodeError> = codec.decode(bytes);
Chaining Operations
Use .andThen() for roundtrip operations:
codec
.encode(value)
.andThen((bytes) => codec.decode(bytes))
.match(
(decoded) => console.log("Success:", decoded),
(err) => console.error("Failed:", err.message),
);
Type Safety
The codec enforces types at compile time:
const userCodec = createCodec(UserSchema);
// TypeScript error: missing 'name' property
userCodec.encode({ id: 1 });
// TypeScript error: 'age' is not a number
userCodec.encode({ id: 1, name: "Alice", age: "thirty" });
Next Steps
Learn about Optional Fields for nullable values.