我正在使用 Warp 设置 Juniper GraphQL 服务器,我需要在 Context 上初始化 mongodb 数据库连接。我对 Rust 很陌生,所以不确定正确的方法。我目前正在尝试await
设置上下文,然后move
使用闭包进入状态,但出现错误:
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
--> src/main.rs:20:33
|
20 | let state = warp::any().map(move || context);
| --- ^^^^^^^^-------
| | | |
| | | closure is `FnOnce` because it moves the variable `context` out of its environment
| | this closure implements `FnOnce`, not `Fn`
| the requirement to implement `Fn` derives from here
我正在使用的代码是:
let context = graph::Context::new().await;
let state = warp::any().map(move || context);
let graphql_filter = juniper_warp::make_graphql_filter(
graph::schema(),
state.boxed(),
);
我像这样设置mongodb连接:
impl Context {
pub async fn new() -> Context {
let db_name = "dbname";
let collection_name = "colname";
let connection_string = "mongodb://...";
let client =
MongoClient::connect(&connection_string).await;
Context {
db: Mongo::new(
db_name.to_string(),
collection_name.to_string(),
client.unwrap(),
),
}
}
}
我似乎无法await
进入闭包内部,并且在闭包外部定义上下文给了我这个错误。实现这一点的正确方法是什么?
编辑:删除了关于 E0525 的评论