diff options
author | Santo Cariotti <santo@dcariotti.me> | 2021-03-16 14:19:42 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-03-16 14:19:42 +0100 |
commit | 896ab2a9fb4a34d82c70792a1114ac1a0f4ad6c0 (patch) | |
tree | 6884cfe0cb85ffee94095d1e9db3864476c24de4 /src/email/routes.rs | |
parent | b950072a3109d2c13881611a3950baa191caf097 (diff) | |
parent | fc28f445d4cfbfcd597438ab2cdd137fa2021dbc (diff) |
Merge pull request #13 from gico-net/feat/add-emails
Manage emails and their hashes for Gravatar
Diffstat (limited to 'src/email/routes.rs')
-rw-r--r-- | src/email/routes.rs | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/src/email/routes.rs b/src/email/routes.rs new file mode 100644 index 0000000..14299eb --- /dev/null +++ b/src/email/routes.rs @@ -0,0 +1,75 @@ +use std::collections::HashMap; + +use crate::config::AppState; +use crate::email::models::{Email, EmailData}; +use crate::errors::AppErrorResponse; +use actix_web::{web, HttpRequest, HttpResponse, Responder}; +use slog::info; + +/// Endpoint used for retrieve all emails +async fn index(state: web::Data<AppState>) -> impl Responder { + let result = Email::find_all(state.pool.clone()).await; + info!(state.log, "GET /email/"); + + match result { + Ok(emails) => HttpResponse::Ok().json(emails), + _ => HttpResponse::BadRequest().json(AppErrorResponse { + detail: "Error trying to read all emails from database" + .to_string(), + }), + } +} + +// Endpoint used for create new email +async fn create_email( + payload: web::Json<EmailData>, + state: web::Data<AppState>, +) -> impl Responder { + info!(state.log, "POST /email/"); + let result = Email::create(state.pool.clone(), &payload).await; + + result + .map(|email| HttpResponse::Created().json(email)) + .map_err(|e| e) +} + +// Endpoint used for email search +async fn search_email( + req: HttpRequest, + state: web::Data<AppState>, +) -> impl Responder { + let query = + web::Query::<HashMap<String, String>>::from_query(req.query_string()) + .unwrap(); + let email = match query.get("q") { + Some(x) => x, + None => { + return HttpResponse::NotFound().json(AppErrorResponse { + detail: "No email found".to_string(), + }); + } + }; + let result = Email::search(state.pool.clone(), email).await; + info!(state.log, "GET /email/search?q={}", email); + + match result { + Ok(email) => HttpResponse::Ok().json(email), + _ => HttpResponse::NotFound().json(AppErrorResponse { + detail: "No email found".to_string(), + }), + } +} +pub fn config(cfg: &mut web::ServiceConfig) { + cfg.service( + web::scope("/email") + .service( + web::resource("{_:/?}") + .route(web::get().to(index)) + .route(web::post().to(create_email)), + ) + .service( + web::resource("/search{_:/?}") + .route(web::get().to(search_email)), + ), + ); +} |