Module async_graphql::dataloader[][src]

This is supported on crate feature dataloader only.
Expand description

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

tokio::runtime::Runtime::new().unwrap().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

Data loader.

LRU cache.

No cache.

Traits

Factory for creating cache storage.

Cache storage for [DataLoader].

Trait for batch loading.