split messages up based on state, refactored backend to decouple states more
This commit is contained in:
@@ -5,12 +5,12 @@ pub type Player {
|
||||
Player(name: String, id: Int, score: Int)
|
||||
}
|
||||
|
||||
pub fn serialize(player: Player) -> List(#(String, json.Json)) {
|
||||
[
|
||||
pub fn serialize(player: Player) -> json.Json {
|
||||
json.object([
|
||||
#("name", json.string(player.name)),
|
||||
#("id", json.int(player.id)),
|
||||
#("score", json.int(player.score)),
|
||||
]
|
||||
])
|
||||
}
|
||||
|
||||
pub fn decoder() -> decode.Decoder(Player) {
|
||||
|
||||
@@ -1,30 +1,37 @@
|
||||
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: List(player.Player))
|
||||
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.array(
|
||||
list.map(session.players, fn(p) { player.serialize(p) }),
|
||||
of: json.object,
|
||||
),
|
||||
),
|
||||
#("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.list(player.decoder()))
|
||||
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:))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user