42 lines
1.1 KiB
Gleam
42 lines
1.1 KiB
Gleam
import gleam/dict
|
|
import gleam/dynamic/decode
|
|
import gleam/int
|
|
import gleam/json
|
|
import gleam/list
|
|
import player
|
|
|
|
pub type Session {
|
|
Session(id: String, host_user_id: Int, players: dict.Dict(Int, player.Player))
|
|
}
|
|
|
|
pub fn serialize(session: Session) -> json.Json {
|
|
json.object([
|
|
#("id", json.string(session.id)),
|
|
#("host_user_id", json.int(session.host_user_id)),
|
|
#("players", json.dict(session.players, int.to_string, player.serialize)),
|
|
])
|
|
}
|
|
|
|
pub fn decoder() -> decode.Decoder(Session) {
|
|
use id <- decode.field("id", decode.string)
|
|
use host_user_id <- decode.field("host_user_id", decode.int)
|
|
use players <- decode.field(
|
|
"players",
|
|
decode.dict(decode.string, player.decoder()),
|
|
)
|
|
|
|
let players =
|
|
dict.to_list(players)
|
|
|> list.map(fn(entry) {
|
|
let assert Ok(key) = int.parse(entry.0)
|
|
#(key, entry.1)
|
|
})
|
|
|> dict.from_list
|
|
|
|
decode.success(Session(id:, host_user_id:, players:))
|
|
}
|
|
|
|
pub fn deseralize(json_string: String) -> Result(Session, json.DecodeError) {
|
|
json.parse(from: json_string, using: decoder())
|
|
}
|