I can't capture the DB reference

250 views Asked by At

I'm trying to create an API using Actix-web, async-grahpql and sqlx with postgresql

In the QueryRoot of the async-graphql I am trying to capture the reference of the DB and make the query the database with sqlx, but it gives me an error

 let items = Todo::list(&pool).await?;
   |                                ^^^^^ expected struct `sqlx::Pool`, found enum `std::result::Result`

Here I want to capture the reference

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

Here I define the references

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

What am I doing wrong? The complete code can be found here.

1

There are 1 answers

0
kmdreko On BEST ANSWER

ctx.data::<T>() returns a Result wrapping a reference to T. You probably want.

let pool = ctx.data::<PgPool>()?;
                            // ^ return on Err, otherwise yield the &PgPool
let items = Todo::list(pool).await?;
                    // ^^^^ shouldn't need & here