iT邦幫忙

2023 iThome 鐵人賽

DAY 14
0
Software Development

當rust 遇上 cqrs & es系列 第 14

D14 加persist層

  • 分享至 

  • xImage
  •  

資料儲存層打算試試SurrealDB,還滿酷的一個資料庫的實作,核心是使用rust編寫的,同時支援關聯式文件式圖式等不同的資料庫型態。

先寫放置事件的repository:

pub struct SurrealEventRepository {
    pub db: Surreal<Db>,
}

impl From<surrealdb::Error> for PersistenceError {
    fn from(err: surrealdb::Error) -> Self {
        Self::UnknownError(Box::new(err))
    }
}

實作PersistedEventRepository trait

#[async_trait]
impl PersistedEventRepository for SurrealEventRepository {
    async fn get_events<A: Aggregate>(&self, aggregate_id: &str) -> Result<Vec<SerializedEvent>, PersistenceError> {
        let result = self.db
            .query("SELECT * FROM events WHERE aggregate_id = $id")
            .bind(("id", aggregate_id))
            .await?
            .take(0)?;
        Ok(result)
    }

    async fn get_last_events<A: Aggregate>(&self, aggregate_id: &str, last_sequence: usize) -> Result<Vec<SerializedEvent>, PersistenceError> {
        let result = self.db
            .query("SELECT * FROM events WHERE aggregate_id = $id AND sequence > $last_sequence")
            .bind(("id", aggregate_id))
            .await?
            .take(0)?;
        Ok(result)
    }

    async fn get_snapshot<A: Aggregate>(&self, aggregate_id: &str) -> Result<Option<SerializedSnapshot>, PersistenceError> {
        todo!()
    }

    async fn persist<A: Aggregate>(&self, events: &[SerializedEvent], snapshot_update: Option<(String, Value, usize)>) -> Result<(), PersistenceError> {
        let event = events.first().unwrap();
        let s :surrealdb::method::Content<'_, Db, &SerializedEvent, Vec<SerializedEvent>>  = self.db
            .create("events")
            .content(event)
            .await?;
        Ok(())
    }

    async fn stream_events<A: Aggregate>(&self, aggregate_id: &str) -> Result<ReplayStream, PersistenceError> {
        todo!()
    }

    async fn stream_all_events<A: Aggregate>(&self) -> Result<ReplayStream, PersistenceError> {
        todo!()
    }
}

上一篇
D13 測試 reader query
下一篇
D15 測一下surrealDB
系列文
當rust 遇上 cqrs & es30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言