3

I'm trying to use Actix-SQLx-Juniper in my Rust project. I've followed and combined any tutorial that I've found, it successfully compiled and run. But when I try to post a query, I got this error in terminal:

thread 'actix-web' panicked at 'Tried to resolve async field users on type Some("Query") with a sync resolver', src/graphql.rs:15:1

and my GraphiQL shows "Thread pool is gone"


this is the src/graphql.rs:

#[derive(Clone, Debug)]
pub struct Context {
    pub pool: PgPool,
}

impl juniper::Context for Context {}

pub struct Query;

#[graphql_object(Context = Context)] // this is line 15
impl Query {
    fn apiVersion() -> &str {
        "1.0"
    }
    #[graphql(description = "Hello")]
    pub async fn users(ctx: &Context) -> FieldResult<Vec<User>> {
        println!("{:#?}", ctx);
        sqlx::query_as::<_, User>("SELECT * FROM users")
            .fetch_all(&ctx.pool)
            .await
            .map_err(|e| e.into())
    }
}

pub type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>;

pub fn create_schema() -> Schema {
    Schema::new(Query {}, EmptyMutation::new(), EmptySubscription::new())
}

But after I trace the error, it panicked when I tried to use execute_sync in my src/handler.rs:

pub fn graphql_handlers(config: &mut ServiceConfig) {
    config
        .data(create_schema())
        .route("/graphql", web::get().to(graphql_playground))
        .route("/graphql", web::post().to(graphql));
}

...
...

async fn graphql(
    pool: web::Data<PgPool>,
    schema: web::Data<Schema>,
    data: web::Json<GraphQLRequest>,
) -> Result<HttpResponse, Error> {
    let ctx = Context {
        pool: pool.get_ref().to_owned(),
    };

    let res = block(move || {
        let res = data.execute_sync(&schema, &ctx);
        Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?)
    })
    .await
    .map_err(Error::from)?;

    Ok(HttpResponse::Ok()
        .content_type("application/json")
        .body(res))
}

I've tried to find the solution or boilerplate code but still couldn't find it.


Here's my main.rs:

#[actix_web::main]
async fn main() -> Result<()> {
    let pool = create_pool().await.expect("Failed connecting to postgres");

    HttpServer::new(move || {
        App::new()
            .data(pool.clone())
            .wrap(Logger::default())
            .configure(graphql_handlers)
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

Here's my dependencies:

actix-web = "3"
juniper = "0.15"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.64"
uuid = { version = "0.8", features = [ "serde", "v4"] }
sqlx = { version = "0.4", features = [ "runtime-actix-rustls", "postgres", "uuid" ] }
smitop
  • 4,770
  • 2
  • 20
  • 53

0 Answers0