diff --git a/services/reports/src/database/client.rs b/services/reports/src/database/client.rs new file mode 100644 index 000000000..72064a72b --- /dev/null +++ b/services/reports/src/database/client.rs @@ -0,0 +1,75 @@ +use comm_services_lib::database::{ + self, batch_operations::ExponentialBackoffConfig, +}; + +use crate::report_types::ReportID; + +use super::constants::*; +use super::item::ReportItem; + +#[derive(serde::Serialize)] +pub struct ReportsPage { + pub reports: Vec, + /// Report ID that can be used as a cursor to retrieve the next page + #[serde(rename(serialize = "nextPage"))] + pub last_evaluated_report: Option, +} + +#[derive(Clone)] +pub struct DatabaseClient { + ddb: aws_sdk_dynamodb::Client, +} + +impl DatabaseClient { + pub fn new(aws_config: &aws_config::SdkConfig) -> Self { + DatabaseClient { + ddb: aws_sdk_dynamodb::Client::new(aws_config), + } + } + + /// Gets a single [`ReportItem`] given its [`ReportID`] + pub async fn get_report( + &self, + report_id: &ReportID, + ) -> Result, database::Error> { + let response = self + .ddb + .get_item() + .table_name(TABLE_NAME) + .key(ATTR_REPORT_ID, report_id.into()) + .send() + .await + .map_err(|err| database::Error::AwsSdk(err.into()))?; + + response + .item + .map(ReportItem::try_from) + .transpose() + .map_err(database::Error::from) + } + + /// Saves multiple reports to DB in batch + pub async fn save_reports( + &self, + reports: impl IntoIterator, + ) -> Result<(), database::Error> { + use aws_sdk_dynamodb::types::{PutRequest, WriteRequest}; + + let requests = reports + .into_iter() + .map(|item| { + let attrs = item.into_attrs(); + let put_request = PutRequest::builder().set_item(Some(attrs)).build(); + WriteRequest::builder().put_request(put_request).build() + }) + .collect::>(); + + database::batch_operations::batch_write( + &self.ddb, + TABLE_NAME, + requests, + ExponentialBackoffConfig::default(), + ) + .await + } +} diff --git a/services/reports/src/database/mod.rs b/services/reports/src/database/mod.rs index ec3751eb7..be61f52db 100644 --- a/services/reports/src/database/mod.rs +++ b/services/reports/src/database/mod.rs @@ -1,14 +1,15 @@ +pub mod client; pub mod item; mod constants { pub const TABLE_NAME: &str = "reports-service-reports"; pub const ATTR_REPORT_ID: &str = "reportID"; pub const ATTR_USER_ID: &str = "userID"; pub const ATTR_REPORT_TYPE: &str = "type"; pub const ATTR_PLATFORM: &str = "platform"; pub const ATTR_BLOB_INFO: &str = "blobInfo"; pub const ATTR_REPORT_CONTENT: &str = "content"; pub const ATTR_ENCRYPTION_KEY: &str = "encryptionKey"; pub const ATTR_CREATION_TIME: &str = "creationTime"; }