How to setup an async Database connection on the Context in Juniper Warp

312 Views Asked by At

I am setting up a Juniper GraphQL server with Warp and I need to initialise a mongodb Database connection on the Context. I am very new to Rust so not sure the right way to do this. I am currently attempting to await the setup of the context and then move it into state using a closure but I get the error:

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

The code I am using is:

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(),
);

I setup the mongodb connection like this:

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(),
            ),
        }
    }
}

I can't seem to await inside the closure and defining the context outside the closure gives me this error. What's the right way to implement this?

Edit: Removed comment about E0525

0

There are 0 best solutions below