-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupcasting.rs
More file actions
101 lines (89 loc) · 2.46 KB
/
Copy pathupcasting.rs
File metadata and controls
101 lines (89 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//! Demonstrates registering sync + async upcasters with Rillflow.
use async_trait::async_trait;
use rillflow::{
Event, Expected, Store,
upcasting::{AsyncUpcaster, Upcaster, UpcasterRegistry},
};
use serde_json::{Value, json};
use sqlx::PgPool;
use uuid::Uuid;
#[tokio::main]
async fn main() -> rillflow::Result<()> {
let database_url =
std::env::var("DATABASE_URL").expect("set DATABASE_URL pointing to your Postgres");
let mut registry = UpcasterRegistry::new();
registry.register(OrderPlacedV1ToV2);
registry.register_async(OrderPlacedV2ToV3);
let store = Store::builder(&database_url)
.upcasters(registry)
.build()
.await?;
let stream_id = Uuid::new_v4();
store
.events()
.append_stream(
stream_id,
Expected::Any,
vec![Event::new(
"OrderPlaced",
&json!({"order_id": 42, "customer_id": "abc123"}),
)],
)
.await?;
let envelope = store
.events()
.read_stream_envelopes(stream_id)
.await?
.pop()
.expect("event inserted");
println!("type={} version={}", envelope.typ, envelope.event_version);
println!("{}", serde_json::to_string_pretty(&envelope.body)?);
Ok(())
}
#[derive(Clone)]
struct OrderPlacedV1ToV2;
impl Upcaster for OrderPlacedV1ToV2 {
fn from_type(&self) -> &str {
"OrderPlaced"
}
fn from_version(&self) -> i32 {
1
}
fn to_type(&self) -> &str {
"OrderPlaced"
}
fn to_version(&self) -> i32 {
2
}
fn upcast(&self, body: &Value) -> rillflow::Result<Value> {
let mut updated = body.clone();
updated["currency"] = json!("USD");
Ok(updated)
}
}
struct OrderPlacedV2ToV3;
#[async_trait]
impl AsyncUpcaster for OrderPlacedV2ToV3 {
fn from_type(&self) -> &str {
"OrderPlaced"
}
fn from_version(&self) -> i32 {
2
}
fn to_type(&self) -> &str {
"OrderPlaced"
}
fn to_version(&self) -> i32 {
3
}
async fn upcast(&self, body: &Value, pool: &PgPool) -> rillflow::Result<Value> {
let mut updated = body.clone();
let id = body["customer_id"].as_str().unwrap_or_default();
let label: String = sqlx::query_scalar("select upper($1::text)")
.bind(id)
.fetch_one(pool)
.await?;
updated["customer_label"] = json!(label);
Ok(updated)
}
}