[][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 for MyLoader {
    type Key = i32;
    type Value = String;
    type Error = Infallible;

    async fn load(&self, keys: HashSet<Self::Key>) -> Result<HashMap<Self::Key, 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::build(Query, EmptyMutation, EmptySubscription)
        .data(DataLoader::new(MyLoader))
        .finish();

    let res = schema.execute(r#"
        {
            v1: value(n: 1)
            v2: value(n: 2)
            v3: value(n: 3)
            v4: value(n: 4)
            v5: value(n: 5)
        }
    "#).await.into_result().unwrap().data;

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

Structs

CachedLoader

Loader for the cached method.

DataLoader

Data loader.

LruCache

Memory-based LRU cache.

Traits

CacheStorage

Cache storage for a loader.

Loader

Trait for batch loading.