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

Values

pub fn bool() -> Codec(Bool)
pub fn float() -> Codec(Float)
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 int() -> Codec(Int)
pub fn list(of item: Codec(a)) -> Codec(List(a))
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.

pub fn optional(of item: Codec(a)) -> Codec(option.Option(a))

None is encoded as null.

pub fn string() -> Codec(String)
pub fn to_string(codec: Codec(a), value: a) -> String

The value as a JSON string.

✨ Search Document