Skip to content

Commit

Permalink
Merge pull request #10 from MiSArch/delete-shopping-cart-items
Browse files Browse the repository at this point in the history
Delete shoppingcart items on order created event
  • Loading branch information
legendofa authored Apr 16, 2024
2 parents 1180516 + 1d138dc commit ccb9c00
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ mongodb-cursor-pagination = "0.3.2"
json = "0.12.4"
log = "0.4.20"
simple_logger = "4.3.3"
serde_json = "1.0.113"
serde_json = "1.0.113"
76 changes: 71 additions & 5 deletions src/http_event_service.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::{debug_handler, extract::State, http::StatusCode, Json};
use bson::Uuid;
use bson::{doc, Uuid};
use log::info;
use mongodb::Collection;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -28,11 +28,12 @@ impl Default for TopicEventResponse {
}
}


/// Relevant part of Dapr event wrapped in a CloudEnvelope.
#[derive(Deserialize, Debug)]
pub struct Event {
pub struct Event<T> {
pub topic: String,
pub data: EventData,
pub data: T,
}

/// Relevant part of Dapr event.data.
Expand All @@ -41,6 +42,27 @@ pub struct EventData {
pub id: Uuid,
}


#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct OrderEventData {
/// Order UUID.
pub id: Uuid,
/// UUID of user connected with Order.
pub user_id: Uuid,
/// OrderItems associated with the order.
pub order_items: Vec<OrderItemEventData>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct OrderItemEventData {
/// UUID of shopping cart item associated with OrderItem.
pub shopping_cart_item_id: Uuid,
/// Specifies the quantity of the OrderItem.
pub count: u64,
}

/// Service state containing database connections.
#[derive(Clone)]
pub struct HttpEventServiceState {
Expand All @@ -60,14 +82,19 @@ pub async fn list_topic_subscriptions() -> Result<Json<Vec<Pubsub>>, StatusCode>
topic: "catalog/product-variant/created".to_string(),
route: "/on-topic-event".to_string(),
};
Ok(Json(vec![pubsub_user, pubsub_product_variant]))
let pubsub_order = Pubsub {
pubsubname: "pubsub".to_string(),
topic: "order/order/created".to_string(),
route: "/on-order-creation-event".to_string(),
};
Ok(Json(vec![pubsub_user, pubsub_product_variant, pubsub_order]))
}

/// HTTP endpoint to receive events.
#[debug_handler(state = HttpEventServiceState)]
pub async fn on_topic_event(
State(state): State<HttpEventServiceState>,
Json(event): Json<Event>,
Json(event): Json<Event<EventData>>,
) -> Result<Json<TopicEventResponse>, StatusCode> {
info!("{:?}", event);

Expand All @@ -88,6 +115,45 @@ pub async fn on_topic_event(
Ok(Json(TopicEventResponse::default()))
}

/// HTTP endpoint to receive user Order creation events.
#[debug_handler(state = HttpEventServiceState)]
pub async fn on_order_creation_event(
State(state): State<HttpEventServiceState>,
Json(event): Json<Event<OrderEventData>>,
) -> Result<Json<TopicEventResponse>, StatusCode> {
info!("{:?}", event);

match event.topic.as_str() {
"order/order/created" => {
delete_ordered_shoppingcart_items_in_mongodb(&state.user_collection, event.data).await?
}
_ => return Err(StatusCode::INTERNAL_SERVER_ERROR),
}
Ok(Json(TopicEventResponse::default()))
}

/// Removes ordered shopping cart items from the users shopping cart.
pub async fn delete_ordered_shoppingcart_items_in_mongodb(collection: &Collection<User>, order_event_data: OrderEventData) -> Result<(), StatusCode> {
let shoppingcart_item_ids: Vec<Uuid> = order_event_data.order_items.iter().map(|o| o.shopping_cart_item_id).collect();
match collection
.update_one(
doc! {"_id": order_event_data.user_id },
doc! {"$pull": {
"shoppingcart.internal_shoppingcart_items": {
"_id": {
"$in": shoppingcart_item_ids
}
}
}},
None,
)
.await
{
Ok(_) => Ok(()),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}

/// Add a newly created product variant to MongoDB.
pub async fn add_product_variant_to_mongodb(
collection: Collection<ProductVariant>,
Expand Down
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use axum::{
routing::{get, post},
Router, Server,
};
use bson::Uuid;
use clap::{arg, command, Parser};
use simple_logger::SimpleLogger;

Expand All @@ -35,7 +36,7 @@ use user::User;
mod authentication;

mod http_event_service;
use http_event_service::{list_topic_subscriptions, on_topic_event, HttpEventServiceState};
use http_event_service::{delete_ordered_shoppingcart_items_in_mongodb, list_topic_subscriptions, on_order_creation_event, on_topic_event, HttpEventServiceState, OrderEventData, OrderItemEventData};

use foreign_types::ProductVariant;

Expand Down Expand Up @@ -78,6 +79,10 @@ async fn build_dapr_router(db_client: Database) -> Router {
// Define routes.
let app = Router::new()
.route("/dapr/subscribe", get(list_topic_subscriptions))
.route(
"/on-order-creation-event",
post(on_order_creation_event),
)
.route("/on-topic-event", post(on_topic_event))
.with_state(HttpEventServiceState {
product_variant_collection,
Expand Down

0 comments on commit ccb9c00

Please sign in to comment.