bison

Package Version Hex Docs

bison (formerly gleam_bson)

bson encoder and decoder for gleam

Quick start

gleam test  # Run the tests
gleam shell # Run an Erlang shell

Installation

gleam add bison

Roadmap

Usage

Encoding

import gleam/list
import gleam/result
import bison/md5
import bison/bson
import bison.{encode}
import bison/object_id

fn calf_to_bson(calf: Calf) -> Result(BitArray, Nil) {
 use id <- result.then(object_id.from_string(calf.id))
 use checksum <- result.then(md5.from_string(calf.checksum))

 Ok(encode([
   #("id", bson.ObjectId(id)),
   #("name", bson.Str(calf.name)),
   #("age", bson.Int32(calf.age)),
   #("weight", bson.Double(calf.weight)),
   #("birthdate", bson.DateTime(calf.birthdate)),
   #("is_healthy", bson.Boolean(calf.is_healthy)),
   #("checksum", bson.Binary(bson.MD5(checksum))),
   #("nicknames", bson.Array(list.map(calf.nicknames, bson.Str))),
 ]))
}

Decoding

import gleam/list
import gleam/result
import bison/md5
import bison/bson
import bison.{decode}
import bison/object_id

fn calf_from_bson(data: BitArray) -> Result(Calf, Nil) {
 use doc <- result.then(decode(data))

 let [
   #("id", bson.ObjectId(id)),
   #("age", bson.Int32(age)),
   #("name", bson.Str(name)),
   #("weight", bson.Double(weight)),
   #("nicknames", bson.Array(nicknames)),
   #("birthdate", bson.DateTime(birthdate)),
   #("is_healthy", bson.Boolean(is_healthy)),
   #("checksum", bson.Binary(bson.MD5(checksum))),
 ] = doc

 Ok(Calf(
   id: object_id.to_string(id),
   age: age,
   name: name,
   weight: weight,
   nicknames: list.map(
     nicknames,
     fn(n) {
       let assert bson.Str(n) = n
       n
     },
   ),
   birthdate: birthdate,
   is_healthy: is_healthy,
   checksum: md5.to_string(checksum),
 ))
}

Search Document