mirror of
https://github.com/graphql-python/graphene.git
synced 2025-02-16 11:30:37 +03:00
update on dataloaders
parent
62d77d7bf1
commit
f32e65ada8
|
@ -248,6 +248,76 @@ search=String(
|
|||
required=False,
|
||||
)
|
||||
```
|
||||
### `Dataloaders` are no longer supported for django as they require async views
|
||||
|
||||
Before:
|
||||
|
||||
```python3
|
||||
def resolve_client(root, info, **kwargs):
|
||||
return info.context.loaders.client_by_client_id_loader.load(root["client_id"])
|
||||
```
|
||||
loader definition:
|
||||
```python3
|
||||
from promise import Promise
|
||||
from promise.dataloader import DataLoader
|
||||
from typing import Dict
|
||||
from collections import defaultdict
|
||||
|
||||
from server.domain.entities import Clients
|
||||
|
||||
|
||||
class ClientByClientIdLoader(DataLoader):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.current_user = kwargs.pop("current_user")
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def batch_load_fn(self, client_ids):
|
||||
id_client: Dict[int, Clients.Client] = defaultdict(None)
|
||||
|
||||
clients = Clients.by_ids(
|
||||
current_user=self.current_user,
|
||||
ids=client_ids,
|
||||
)
|
||||
|
||||
for client in clients:
|
||||
id_client[client["id"]] = client
|
||||
|
||||
return Promise.resolve(
|
||||
[id_client.get(client_id, None) for client_id in client_ids]
|
||||
)
|
||||
```
|
||||
|
||||
After (currently this approach won't work) [check this issue](https://stackoverflow.com/questions/76900691/django-working-example-of-graphene-aiodataloader)
|
||||
|
||||
|
||||
```python3
|
||||
from aiodataloader import DataLoader
|
||||
from typing import Dict
|
||||
from collections import defaultdict
|
||||
|
||||
from server.domain.entities import Clients
|
||||
|
||||
|
||||
class ClientByClientIdLoader(DataLoader):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.current_user = kwargs.pop("current_user")
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
async def batch_load_fn(self, client_ids):
|
||||
id_client: Dict[int, Clients.Client] = defaultdict(None)
|
||||
|
||||
clients = Clients.by_ids(
|
||||
current_user=self.current_user,
|
||||
ids=client_ids,
|
||||
)
|
||||
|
||||
for client in clients:
|
||||
id_client[client["id"]] = client
|
||||
|
||||
return [id_client.get(client_id, None) for client_id in client_ids]
|
||||
```
|
||||
|
||||
### Other breaking changes
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user