首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得返回Vec的Axum Handler函数?

如何获得返回Vec的Axum Handler函数?
EN

Stack Overflow用户
提问于 2022-07-28 01:35:11
回答 1查看 603关注 0票数 1

我正在学习如何在SQLx中使用Axum,从这个示例开始。这个基本的例子起作用了,但是我很难继续前进。我正在使用一个简单的数据库表,如下所示:

代码语言:javascript
复制
  todo  | description
--------+--------------
 todo_1 | doing todo 1
 todo_2 | doing todo 2
 todo_3 | doing todo 3

我只是试图返回"SELECT * FROM todos",但是我得到了一个错误。我想我的Result类型的返回是错误的,但我不知道下一步该做什么。main.rs的全部内容如下所示。

代码语言:javascript
复制
//! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-sqlx-postgres
//! ```
//!
//! Test with curl:
//!
//! ```not_rust
//! curl 127.0.0.1:3000
//! curl -X POST 127.0.0.1:3000
//! ```

use axum::{
    async_trait,
    extract::{Extension, FromRequest, RequestParts},
    http::StatusCode,
    routing::get,
    Router,
};
use sqlx::postgres::{PgPool, PgPoolOptions, PgRow};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use std::{net::SocketAddr, time::Duration};

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "example_tokio_postgres=debug".into()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    let db_connection_str = std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgres://postgres:postgres@localhost".to_string());

    // setup connection pool
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect_timeout(Duration::from_secs(3))
        .connect(&db_connection_str)
        .await
        .expect("can connect to database");

    // build our application with some routes
    let app = Router::new()
        .route(
            "/",
            get(using_connection_pool_extractor).post(using_connection_extractor),
        )
        .layer(Extension(pool));

    // run it with hyper
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

// we can extract the connection pool with `Extension`
async fn using_connection_pool_extractor(
    Extension(pool): Extension<PgPool>,
) -> Result<Vec<String>, (StatusCode, String)> {
    sqlx::query_scalar("select * from todos")
        .fetch_one(&pool)
        .await
        .map_err(internal_error)
}

// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Postgres>);

#[async_trait]
impl<B> FromRequest<B> for DatabaseConnection
where
    B: Send,
{
    type Rejection = (StatusCode, String);

    async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
        let Extension(pool) = Extension::<PgPool>::from_request(req)
            .await
            .map_err(internal_error)?;

        let conn = pool.acquire().await.map_err(internal_error)?;

        Ok(Self(conn))
    }
}

async fn using_connection_extractor(
    DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
    let mut conn = conn;
    sqlx::query_scalar("select 'hello world from pg'")
        .fetch_one(&mut conn)
        .await
        .map_err(internal_error)
}

/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
    E: std::error::Error,
{
    (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}

与示例相比,我更改了这个函数,使它返回一个Vec<String>而不是普通的String,但是我得到了一个编译器错误:

代码语言:javascript
复制
async fn using_connection_pool_extractor(
    Extension(pool): Extension<PgPool>,
) -> Result<Vec<String>, (StatusCode, String)> {
    sqlx::query_scalar("select * from todos")
        .fetch_one(&pool)
        .await
        .map_err(internal_error)
}
代码语言:javascript
复制
error[E0277]: the trait bound `fn(Extension<Pool<sqlx::Postgres>>) -> impl Future<Output = Result<Vec<String>, (StatusCode, String)>> {using_connection_pool_extractor}: Handler<_, _>` is not satisfied
   --> src/main.rs:52:17
    |
52  |             get(using_connection_pool_extractor).post(using_connection_extractor),
    |             --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(Extension<Pool<sqlx::Postgres>>) -> impl Future<Output = Result<Vec<String>, (StatusCode, String)>> {using_connection_pool_extractor}`
    |             |
    |             required by a bound introduced by this call
    |
    = help: the trait `Handler<T, ReqBody>` is implemented for `axum::handler::Layered<S, T>`
note: required by a bound in `axum::routing::get`

我不知道这个错误意味着什么,或者它是否与实际问题有关。

EN

回答 1

Stack Overflow用户

发布于 2022-07-28 21:05:46

尝试使用axum::Json

代码语言:javascript
复制
async fn using_connection_pool_extractor(
    Extension(pool): Extension<PgPool>,
) -> Result<axum::Json<Vec<String>>, (StatusCode, String)> {
    sqlx::query_scalar("select * from todos")
        .fetch_one(&pool)
        .await
        .map(|todos| axum::Json(todos))
        .map_err(internal_error)
}

原因是IntoResponse特性在Vec<T>中没有实现。下面是Axum作者的一个较长的答案:https://users.rust-lang.org/t/axum-error-handling-trait-question/65530

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73146289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档