Last active
May 28, 2022 16:17
-
-
Save jayhuang75/b9869164de4c3049de8b606138cadbee to your computer and use it in GitHub Desktop.
rust-nextjs-twitter-streaming-registeration.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let register = warp::path("register"); | |
let register_routes = register | |
.and(warp::post()) | |
.and(warp::body::json()) | |
.and(with_clients(client_store.clone())) | |
.and_then(app::handlers::register_handler) | |
.or(register | |
.and(warp::delete()) | |
.and(warp::path::param()) | |
.and(with_clients(client_store.clone())) | |
.and_then(app::handlers::unregister_handler)); | |
//################################ | |
// Register Handler | |
//################ | |
pub async fn register_handler(body: RegisterRequest, client_store: ClientStore) -> Result<impl Reply> { | |
let user_id = Uuid::parse_str(&body.user_id).unwrap(); | |
let topic = body.topic; | |
let new_client = Client::new(user_id, topic); | |
let uuid = new_client.register(client_store).await; | |
log::info!("new client : {:?} registerd", new_client); | |
Ok(json(&RegisterResponse { | |
user_uuid: format!("{}", uuid), | |
})) | |
} | |
pub async fn unregister_handler(id: String, clients: ClientStore) -> Result<impl Reply> { | |
log::info!("[unregister_handler] unregister user_id {:?}", id); | |
let user_id = Uuid::parse_str(&id).unwrap(); | |
clients | |
.read().await | |
.iter() | |
.filter(|(_, client)| client.user_id == user_id) | |
.for_each(|(_, client)| { | |
if let Some(sender) = &client.sender { | |
log::info!("[unregister_handler] unregister user_id {:?}", id); | |
let _ = sender.send(Ok(Message::close())); | |
} | |
}); | |
clients.write().await.remove(&id); | |
Ok(StatusCode::OK) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment