|
1 |
| -use bb8::Pool; |
| 1 | +use std::convert::Infallible; |
| 2 | + |
| 3 | +use bb8::{Pool, RunError}; |
2 | 4 | use bb8_postgres::PostgresConnectionManager;
|
3 |
| -use futures_util::future::{FutureExt, TryFutureExt}; |
4 | 5 | use hyper::service::{make_service_fn, service_fn};
|
5 | 6 | use hyper::{Body, Error, Response, Server};
|
| 7 | +use tokio_postgres::NoTls; |
6 | 8 |
|
7 | 9 | // Select some static data from a Postgres DB and return it via hyper.
|
8 | 10 | //
|
@@ -31,32 +33,29 @@ async fn main() {
|
31 | 33 | let pool = pool.clone();
|
32 | 34 | async move {
|
33 | 35 | println!("Got request");
|
34 |
| - Ok::<_, Error>( |
35 |
| - pool.get() |
36 |
| - .and_then(|connection| async { |
37 |
| - let select = connection.prepare("SELECT 1").await?; |
38 |
| - Ok((connection, select)) |
39 |
| - }) |
40 |
| - .and_then(|(connection, select)| async move { |
41 |
| - let row = connection.query_one(&select, &[]).await?; |
42 |
| - Ok(row) |
43 |
| - }) |
44 |
| - .map(|result| match result { |
45 |
| - Ok(row) => { |
46 |
| - let v = row.get::<usize, i32>(0); |
47 |
| - println!("Sending success response"); |
48 |
| - Response::new(Body::from(format!("Got results {:?}", v))) |
49 |
| - } |
50 |
| - Err(e) => { |
51 |
| - println!("Sending error response"); |
52 |
| - Response::new(Body::from(format!("Internal error {:?}", e))) |
53 |
| - } |
54 |
| - }) |
55 |
| - .await, |
56 |
| - ) |
| 36 | + Ok::<_, Infallible>(match handler(pool).await { |
| 37 | + Ok(rsp) => { |
| 38 | + println!("Sending success response"); |
| 39 | + rsp |
| 40 | + } |
| 41 | + Err(e) => { |
| 42 | + println!("Sending error response"); |
| 43 | + Response::new(Body::from(format!("Internal error {:?}", e))) |
| 44 | + } |
| 45 | + }) |
57 | 46 | }
|
58 | 47 | }))
|
59 | 48 | }
|
60 | 49 | }))
|
61 | 50 | .await;
|
62 | 51 | }
|
| 52 | + |
| 53 | +async fn handler( |
| 54 | + pool: Pool<PostgresConnectionManager<NoTls>>, |
| 55 | +) -> Result<Response<Body>, RunError<tokio_postgres::Error>> { |
| 56 | + let conn = pool.get().await?; |
| 57 | + let stmt = conn.prepare("SELECT 1").await?; |
| 58 | + let row = conn.query_one(&stmt, &[]).await?; |
| 59 | + let v = row.get::<usize, i32>(0); |
| 60 | + Ok(Response::new(Body::from(format!("Got results {:?}", v)))) |
| 61 | +} |
0 commit comments