pont

Package Version Hex Docs

Two-way serializers for Gleam. Describe the shape of a type once and get a decoder, an encoder, and a schema from it — decode untyped Dynamic data into your type, encode your type to JSON or YAML, and inspect the generated Spec to build documentation or validation on top.

gleam add pont@1
import gleam/dynamic
import gleam/json
import pont/serialize

pub type Person {
  Person(name: String, age: Int)
}

fn person_serializer() -> serialize.Serializer(Person) {
  serialize.object(fn(context) {
    use context, name <- serialize.field(
      context,
      "name",
      serialize.string(),
      fn(person: Person) { person.name },
    )
    use context, age <- serialize.field(
      context,
      "age",
      serialize.int(),
      fn(person: Person) { person.age },
    )

    serialize.build(context, Person(name:, age:))
  })
}

pub fn main() -> Nil {
  let serializer = person_serializer()

  // Decode dynamic data into a typed value.
  let data =
    dynamic.properties([
      #(dynamic.string("name"), dynamic.string("Alice")),
      #(dynamic.string("age"), dynamic.int(30)),
    ])
  let assert Ok(person) = serialize.decode(data, serializer)

  // Encode a typed value straight to JSON.
  person
  |> serialize.encode_json(serializer)
  |> json.to_string
  // -> "{\"name\":\"Alice\",\"age\":30}"
}

Features

Further documentation can be found at https://hexdocs.pm/pont.

Development

gleam run   # Run the project
gleam test  # Run the tests
✨ Search Document