Skip to content

Commit

Permalink
Add load_many to DataLoader (#1528)
Browse files Browse the repository at this point in the history
  • Loading branch information
silas authored Jan 9, 2022
1 parent 1125d07 commit 77d93f4
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
3 changes: 3 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Release type: patch

This release adds `load_many` to `DataLoader`.
7 changes: 7 additions & 0 deletions docs/guides/dataloaders.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ await loader.load(1)

Will result in only one call to `load_users`.

And finally sometimes we'll want to load more than one key at a time. In those
cases we can use the `load_many` method.

```python
[user_a, user_b, user_c] = await loader.load_many([1, 2, 3])
```

## Usage with GraphQL

Let's see an example of how you can use DataLoaders with GraphQL:
Expand Down
17 changes: 15 additions & 2 deletions strawberry/dataloader.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import dataclasses
from asyncio import create_task, get_event_loop
from asyncio import create_task, gather, get_event_loop
from asyncio.events import AbstractEventLoop
from asyncio.futures import Future
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, TypeVar
from typing import (
Any,
Awaitable,
Callable,
Dict,
Generic,
Iterable,
List,
Optional,
TypeVar,
)

from .exceptions import WrongNumberOfResultsReturned

Expand Down Expand Up @@ -78,6 +88,9 @@ def load(self, key: K) -> Awaitable[T]:

return future

def load_many(self, keys: Iterable[K]) -> Awaitable[List[T]]:
return gather(*map(self.load, keys))


def should_create_new_batch(loader: DataLoader, batch: Batch) -> bool:
if (
Expand Down
4 changes: 4 additions & 0 deletions tests/test_dataloaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ async def idx(keys):
assert value_b == 2
assert value_c == 3

values = await loader.load_many([1, 2, 3, 4, 5, 6])

assert values == [1, 2, 3, 4, 5, 6]


async def test_gathering(mocker):
async def idx(keys):
Expand Down

0 comments on commit 77d93f4

Please sign in to comment.