From 975888b8d8edfbca8c9be67f52a61b823ea4c3c6 Mon Sep 17 00:00:00 2001
From: Andrew4Coding <andrewdevitoaryo@gmail.com>
Date: Fri, 28 Mar 2025 12:30:30 +0800
Subject: [PATCH] Implement subscribe function in Notification service.

---
 src/service/notification.rs | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/src/service/notification.rs b/src/service/notification.rs
index 5a35cdb..6dd7b84 100644
--- a/src/service/notification.rs
+++ b/src/service/notification.rs
@@ -1,5 +1,6 @@
 use std::thread;
 
+use reqwest::Request;
 use rocket::http::Status;
 use rocket::log;
 use rocket::serde::json::to_string;
@@ -14,4 +15,40 @@ use crate::repository::notification::NotificationRepository;
 pub struct NotificationService;
 
 impl NotificationService {
+    #[tokio::main]
+    async fn subscribe_request(product_type: String) -> Result<SubscriberRequest> {
+        let product_type_upper = product_type.to_uppercase();
+        let product_type_str = product_type_upper.as_str();
+
+        let notification_receiver_url = format!("{}/receive", APP_CONFIG.get_instance_root_url());
+
+        let payload = SubscriberRequest {
+             name: APP_CONFIG.get_instance_name().to_string(),
+             url: notification_receiver_url
+        };
+
+        let request_url = format!("{}/notification/subscribe/{}", APP_CONFIG.get_publisher_root_url(), product_type_str);
+        let request = REQWEST_CLIENT
+            .post(request_url.clone())
+            .header("Content-Type", "application/json")
+            .header("Accept", "application/json")
+            .body(to_string(&payload).unwrap())
+            .send().await;
+
+        log::warn_!("Sent subscribe request to {}", request_url);
+
+        return match request {
+            Ok(f) => match f.json::<SubscriberRequest>().await {
+                Ok(x) => Ok(x),
+                Err(y) => Err(compose_error_response(Status::NotAcceptable,
+                    y.to_string()))
+            },
+            Err(e) => Err(compose_error_response(Status::NotFound, e.to_string()))
+        }
+    }
+
+    pub fn subscribe(product_type: &str) -> Result<SubscriberRequest> {
+        let product_type_clone = String::from(product_type);
+        return thread::spawn(move || Self::subscribe_request(product_type_clone)).join().unwrap();
+    }
 }
\ No newline at end of file
-- 
GitLab