howdy/codec
How to turn a value into JSON and back, as one value. Anything that stores or sends a value and reads it back later takes a codec: a remote procedure’s input and output, or an entry in a cache.
import gleam/dynamic/decode
import gleam/json
import howdy/codec
pub fn user_codec() -> codec.Codec(User) {
codec.new(
encode: fn(user: User) {
json.object([#("id", json.int(user.id)), #("name", json.string(user.name))])
},
decoder: {
use id <- decode.field("id", decode.int)
use name <- decode.field("name", decode.string)
decode.success(User(id:, name:))
},
)
}
The encoder and decoder must agree: decoding what encode produced
gives back the same value.
Types
An encoder and the decoder that reads its output back.
pub type Codec(a) {
Codec(encode: fn(a) -> json.Json, decoder: decode.Decoder(a))
}
Constructors
-
Codec(encode: fn(a) -> json.Json, decoder: decode.Decoder(a))
Values
pub fn from_string(
codec: Codec(a),
text: String,
) -> Result(a, json.DecodeError)
Read a value back from a JSON string to_string produced.
pub fn map(
codec: Codec(a),
from from: fn(b) -> a,
to to: fn(a) -> b,
) -> Codec(b)
A codec for b, by converting to and from a type that already has one.
codec.map(codec.int(), from: fn(id: UserId) { id.value }, to: UserId)
pub fn new(
encode encode: fn(a) -> json.Json,
decoder decoder: decode.Decoder(a),
) -> Codec(a)
A codec from an encoder and a decoder that agree with each other.
pub fn nil() -> Codec(Nil)
For values that carry nothing, such as a procedure with no input.