如何解决我无法捕获数据库参考
我正在尝试使用带有Postgresql的Actix-web,async-grahpql和sqlx创建一个api
在async-graphql的QueryRoot中,我试图捕获数据库的引用,并使用sqlx对该数据库进行查询,但这给我一个错误
let items = Todo::list(&pool).await?;
| ^^^^^ expected struct `sqlx::Pool`,found enum `std::result::Result`
我要在这里捕获参考
use crate::todo::*;
use async_graphql::{Context,FieldResult};
use sqlx::postgres::PgPool;
pub struct QueryRoot;
#[async_graphql::Object]
impl QueryRoot {
async fn todos(&self,ctx: &Context<'_>) -> FieldResult<Vec<Todo>> {
let pool = ctx.data::<PgPool>();
let items = Todo::list(&pool).await?; //<-- This line generates an error
Ok(items)
}
}
在这里定义引用
pub fn run(listener: TcpListener,db_pool: PgPool) -> Result<Server,std::io::Error> {
let data_db_pool = Data::new(db_pool);
//GraphQL
let schema = Schema::build(QueryRoot,MutationRoot,EmptySubscription)
.data(data_db_pool.clone()) //<- DB reference
.finish();
let server = HttpServer::new(move || {
App::new()
.app_data(db_pool.clone()) //<- DB reference
.data(schema.clone())
.route("/graphql",web::post().to(graphql))
.route("/graphql",web::get().to(graphql_playground))
})
.listen(listener)?
.run();
Ok(server)
}
我在做什么错了?
解决方法
ctx.data::<T>()
返回一个Result
,其中包含对T
的引用。你可能想要。
let pool = ctx.data::<PgPool>()?;
// ^ return on Err,otherwise yield the &PgPool
let items = Todo::list(pool).await?;
// ^^^^ shouldn't need & here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。