tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

53 lignes · 1526 octetsBrut · Historique
1/// The example aggregate: a counter. `decide` and `evolve` are pure; the
2/// store is the `event_store` effect, so the same code runs against
3/// memory in tests and PostgreSQL in production.
4
5import std/bytes
6import std/list
7import std/result
8import std/string
9
10import event_store.{type Event, type NewEvent, type event_store, NewEvent}
11
12/// The counter's commands.
13pub type Command { Increment(by: Int) }
14
15/// The command handler's flow: load the stream, evolve the state, decide,
16/// append at the version we read.
17pub fn increment ::
18 stream: String
19 by: Int
20 -> Result<Int, event_store.StoreError> / <event_store>
21{
22 use events <- result.try (event_store.load stream)
23 let state = list.fold events 0 fn s e { evolve s e }
24 use decided <-
25 result.try
26 (decide Increment(by) state |> result.map_error event_store.Store)
27 event_store.append stream (list.length events) decided
28}
29
30/// What a command decides, given the state. Payloads are bytes (the
31/// column is `bytea`); the counter's are the text of the increment.
32pub fn decide :: command: Command state: Int -> Result<List<NewEvent>, String>
33{
34 match command
35 { Increment(by) -> if by <= 0
36 {
37 Error("increments are positive")
38 }
39 else
40 {
41 Ok([NewEvent("incremented", bytes.from_string "{by}")])
42 }
43 }
44}
45
46/// The state after an event.
47pub fn evolve :: state: Int event: Event -> Int
48{
49 match bytes.to_string event.data
50 { Ok(s) -> match string.to_int s { Ok(n) -> state + n, Error(_) -> state }
51 , Error(_) -> state
52 }
53}