Should I use dataloaders in relay.Node.resolve_nodes?

I've got a node type like this:
@strawberry.type(name="Todo")
class TodoType(BaseNodeType):
content: str
completed: bool
created_at: datetime
updated_at: datetime | None

@classmethod
def from_orm(cls, todo: Todo) -> Self:
"""Construct a node from an ORM instance."""
return cls(
id=todo.id,
content=todo.content,
completed=todo.completed,
created_at=todo.created_at,
updated_at=todo.updated_at,
)

@classmethod
async def resolve_nodes( # noqa: ANN206
cls,
*,
info: Info,
node_ids: Iterable[str],
required: bool = False, # noqa: ARG003
):
todos = await info.context.loaders.todo_by_id.load_many(node_ids)
return list(map(cls.from_orm, [todo for todo in todos if todo is not None]))
@strawberry.type(name="Todo")
class TodoType(BaseNodeType):
content: str
completed: bool
created_at: datetime
updated_at: datetime | None

@classmethod
def from_orm(cls, todo: Todo) -> Self:
"""Construct a node from an ORM instance."""
return cls(
id=todo.id,
content=todo.content,
completed=todo.completed,
created_at=todo.created_at,
updated_at=todo.updated_at,
)

@classmethod
async def resolve_nodes( # noqa: ANN206
cls,
*,
info: Info,
node_ids: Iterable[str],
required: bool = False, # noqa: ARG003
):
todos = await info.context.loaders.todo_by_id.load_many(node_ids)
return list(map(cls.from_orm, [todo for todo in todos if todo is not None]))
Should I be using dataloaders to resolve my nodes here? If so, should I use a separate dataloader when required=False and a separate dataloader when required=True? Or am I completely wrong and should I just use my repository layer directly here?
6 Replies
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Aryan Iyappan
Aryan Iyappan3mo ago
Oh, right! Thank you! So my doubt is.. is it a common pattern to implement two separate dataloaders: one which raises an error and another one which does not?
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Aryan Iyappan
Aryan Iyappan3mo ago
off the top of my head, I think it would be nice if we could somehow pass the required argument to the dataloader, something like:
dataloader.load_many(keys, required=True)
dataloader.load_many(keys, required=True)
so that the dataloader fetch function can handle this logic..
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Aryan Iyappan
Aryan Iyappan3mo ago
Oh that's actually a brilliant idea!
Want results from more Discord servers?
Add your server