additional params in dataloader #1681
Replies: 2 comments
-
I was able to get it to work with aiodataloader https://pypi.org/project/aiodataloader/ I created a custom DataLoader class that inits the database connection and then used the batch_load_fn which I can then access the database. Strawberry should do something similar or just pass the info context, that would help a lot in doing things. |
Beta Was this translation helpful? Give feedback.
-
Sorry to ping this old thread but wanted to share a workaround with Strawberry Dataloader. The idea is to use callable classes already initialised with required variables. Good place to do it in the context getter. Example with using Google Cloud Firestore: from typing import List, Union, Tuple, TYPE_CHECKING
from strawberry.dataloader import DataLoader
from app.core.config import settings
if TYPE_CHECKING:
from strawberry.types import Info
from google.cloud.firestore import AsyncClient
class MyCustomCallable:
def __init__(self, firestore: "AsyncClient"):
self.firestore = firestore
async def __call__(self, keys: List[str]) -> List[List[Tuple[float, float]]]:
print(self.firestore) # Accessible here
return [[(1.0, 2.0), (3.0, 4.0)] for _ in keys] # Example callable querying coordiantes in Firestore
def create_loader(firestore: "AsyncClient") -> DataLoader:
return DataLoader(load_fn=MyCustomCallable(firestore=firestore), max_batch_size=settings.MAX_BATCH_SIZE) |
Beta Was this translation helpful? Give feedback.
-
It's not immediately clear how the DataLoader get passed in additional params like a db object to fetch data from keys
Do i need to make the load_fn some instance method with the db initialized or something?
Beta Was this translation helpful? Give feedback.
All reactions