Skip to content

Utility for batching DB accesses to address GraphQL's N+1 problem.

Notifications You must be signed in to change notification settings

LightSourceAI/dataload-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dataload-rs

dataload-rs is a utility that solves the GraphQL N+1 problem through batch loading.

Example

Add dataload-rs as a dependency:

dataload-rs = "0.1"

Define some batch function and corresponding context (a single context can be shared by multiple batch functions). Then create and use a loader with the BatchFunction.

use async_trait::async_trait;
use dataload_rs::{BatchFunction, Loader};

// Empty functor that implements the BatchFunction trait. For this example, it
// trivially loads values from some HashMap.
struct MyBatchFn;

#[async_trait]
impl BatchFunction<i64, String> for MyBatchFn {
    type Context = HashMap<i64, String>;

    async fn load(keys: &[i64], context: &Self::Context) -> Vec<(i64, String)> {
        keys.into_iter()
            .filter_map(|k| context.get(k).cloned().map(|v| (*k, v)))
            .collect()
    }
}

#[tokio::main]
async fn main() {
    let mut context = HashMap::new();
    context.insert(2001, "a space odyssey".to_owned());
    context.insert(7, "samurai".to_owned());
    context.insert(12, "angry men".to_owned());

    let loader = Loader::new(MyBatchFn {}, context);

    assert_eq!(loader.load(7).await.as_deref(), Some("samurai"));
    assert_eq!(loader.load(15).await, None);

    assert_eq!(
        loader
            .load_many(vec![12, 2010, 2001])
            .await
            .iter()
            .map(Option::as_deref)
            .collect::<Vec<_>>(),
        vec![Some("angry men"), None, Some("a space odyssey")]
    );
}

About

Utility for batching DB accesses to address GraphQL's N+1 problem.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages