| 10 | |
| 11 | #[tokio::main] |
| 12 | async fn main() { |
| 13 | let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| { |
| 14 | "handle_errors=warn,practical_rust_book=warn,warp=warn".to_owned() |
| 15 | }); |
| 16 | |
| 17 | let store = |
| 18 | store::Store::new("postgres://localhost:5432/rustwebdev").await; |
| 19 | |
| 20 | sqlx::migrate!() |
| 21 | .run(&store.clone().connection) |
| 22 | .await |
| 23 | .expect("Cannot migrate DB"); |
| 24 | |
| 25 | let store_filter = warp::any().map(move || store.clone()); |
| 26 | |
| 27 | tracing_subscriber::fmt() |
| 28 | // Use the filter we built above to determine which traces to record. |
| 29 | .with_env_filter(log_filter) |
| 30 | // Record an event when each span closes. This can be used to time our |
| 31 | // routes' durations! |
| 32 | .with_span_events(FmtSpan::CLOSE) |
| 33 | .init(); |
| 34 | |
| 35 | let cors = warp::cors() |
| 36 | .allow_any_origin() |
| 37 | .allow_header("content-type") |
| 38 | .allow_methods(&[ |
| 39 | Method::PUT, |
| 40 | Method::DELETE, |
| 41 | Method::GET, |
| 42 | Method::POST, |
| 43 | ]); |
| 44 | |
| 45 | let get_questions = warp::get() |
| 46 | .and(warp::path("questions")) |
| 47 | .and(warp::path::end()) |
| 48 | .and(warp::query()) |
| 49 | .and(store_filter.clone()) |
| 50 | .and_then(routes::question::get_questions); |
| 51 | |
| 52 | let update_question = warp::put() |
| 53 | .and(warp::path("questions")) |
| 54 | .and(warp::path::param::<i32>()) |
| 55 | .and(warp::path::end()) |
| 56 | .and(store_filter.clone()) |
| 57 | .and(warp::body::json()) |
| 58 | .and_then(routes::question::update_question); |
| 59 | |
| 60 | let delete_question = warp::delete() |
| 61 | .and(warp::path("questions")) |
| 62 | .and(warp::path::param::<i32>()) |
| 63 | .and(warp::path::end()) |
| 64 | .and(store_filter.clone()) |
| 65 | .and_then(routes::question::delete_question); |
| 66 | |
| 67 | let add_question = warp::post() |
| 68 | .and(warp::path("questions")) |
| 69 | .and(warp::path::end()) |