[][src]Module async_graphql::dataloader

This is supported on crate feature dataloader only.

Batch loading support, used to solve N+1 problem.

Examples

use async_graphql::*;
use async_graphql::dataloader::*;
use std::collections::{HashSet, HashMap};
use std::convert::Infallible;
use async_graphql::dataloader::Loader;

/// This loader simply converts the integer key into a string value.
struct MyLoader;

#[async_trait::async_trait]
impl Loader<i32> for MyLoader {
    type Value = String;
    type Error = Infallible;

    async fn load(&self, keys: &[i32]) -> Result<HashMap<i32, Self::Value>, Self::Error> {
        // Use `MyLoader` to load data.
        Ok(keys.iter().copied().map(|n| (n, n.to_string())).collect())
    }
}

struct Query;

#[Object]
impl Query {
    async fn value(&self, ctx: &Context<'_>, n: i32) -> Option<String> {
        ctx.data_unchecked::<DataLoader<MyLoader>>().load_one(n).await.unwrap()
    }
}

async_std::task::block_on(async move {
    let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
    let query = r#"
        {
            v1: value(n: 1)
            v2: value(n: 2)
            v3: value(n: 3)
            v4: value(n: 4)
            v5: value(n: 5)
        }
    "#;
    let request = Request::new(query).data(DataLoader::new(MyLoader));
    let res = schema.execute(request).await.into_result().unwrap().data;

    assert_eq!(res, value!({
        "v1": "1",
        "v2": "2",
        "v3": "3",
        "v4": "4",
        "v5": "5",
    }));
});

Structs

DataLoader

Data loader.

Traits

Loader

Trait for batch loading.