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
use std::env;

use actix_web::{
    middleware,
    web::{self, Data},
    App, HttpServer,
};
use chekov::prelude::*;
use sqlx::PgPool;

mod account;
mod commands;
mod events;
mod gift_card;
mod http;
mod order;

pub fn init(cfg: &mut web::ServiceConfig) {
    cfg.service(http::create_account);
    cfg.service(http::create_gift_card);
    cfg.service(http::create_order);
    cfg.service(http::add_order_item);
}

#[derive(Default)]
struct DefaultApp {}

impl Application for DefaultApp {
    type Storage = PostgresStorage;
}

#[actix::main]
async fn main() -> std::io::Result<()> {
    tracing_subscriber::fmt::init();

    let db_pool = PgPool::connect("postgresql://postgres:postgres@localhost/gift_shop")
        .await
        .unwrap();

    // Configure the storage (PG, InMemory,...)
    DefaultApp::with_default()
        .listener_url("postgresql://postgres:postgres@localhost/event_store_gift_shop".into())
        .event_handler(account::AccountProjector {
            pool: db_pool.clone(),
        })
        .event_handler(gift_card::GiftCardProjector {
            pool: db_pool.clone(),
        })
        .event_handler(order::OrderProjector {
            pool: db_pool.clone(),
        })
        .storage(PostgresStorage::with_url(
            "postgresql://postgres:postgres@localhost/event_store_gift_shop",
        ))
        .launch()
        .await;

    HttpServer::new(move || {
        App::new()
            .wrap(middleware::Logger::default())
            .app_data(Data::new(db_pool.clone()))
            .app_data(web::JsonConfig::default().limit(4096))
            .configure(init)
    })
    .bind(env::var("RUNTIME_ENDPOINT").expect("Must define the RUNTIME_ENDPOINT"))?
    .run()
    .await?;

    tokio::signal::ctrl_c().await.unwrap();
    println!("Ctrl-C received, shutting down");
    Ok(())
}