Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve field ordering by adding placeholder values for deferred fields #2

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions graphql_sync_dataloaders/execution_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
from .sync_future import SyncFuture


PENDING_FUTURE = object()


class DeferredExecutionContext(ExecutionContext):
"""Execution for working with synchronous Futures.

Expand Down Expand Up @@ -84,12 +87,17 @@ def execute_fields_serially(
results[response_name] = result
else:

# Add placeholder so that field order is preserved
results[response_name] = PENDING_FUTURE

# noinspection PyShadowingNames, PyBroadException
def process_result(response_name: str, result: SyncFuture) -> None:
nonlocal unresolved
awaited_result = result.result()
if awaited_result is not Undefined:
results[response_name] = awaited_result
else:
del results[response_name]
unresolved -= 1
if not unresolved:
future.set_result(results)
Expand Down
67 changes: 67 additions & 0 deletions tests/test_dataloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,70 @@ def resolve_best_friend(user, _):
],
}
assert mock_load_fn.call_count == 1


def test_result_field_ordering():
NAMES = {
"1": "Sarah",
"2": "Lucy",
"3": "Geoff",
"5": "Dave",
}

def load_fn(keys):
return [NAMES[key] for key in keys]

mock_load_fn = Mock(wraps=load_fn)
dataloader = SyncDataLoader(mock_load_fn)

def resolve_name(_, __, key):
return dataloader.load(key)

def resolve_hello(_, __, name):
return f"hello {name}"

schema = GraphQLSchema(
query=GraphQLObjectType(
name="Query",
fields={
"name": GraphQLField(
GraphQLString,
args={
"key": GraphQLArgument(GraphQLString),
},
resolve=resolve_name,
),
"hello": GraphQLField(
GraphQLString,
args={
"name": GraphQLArgument(GraphQLString),
},
resolve=resolve_hello,
)
},
)
)

result = graphql_sync_deferred(
schema,
"""
query {
name1: name(key: "1")
hello1: hello(name: "grace")
name2: name(key: "2")
hello2: hello(name: "lucy")
}
""",
)

assert not result.errors
assert result.data
assert result.data == {
"name1": "Sarah",
"hello1": "hello grace",
"name2": "Lucy",
"hello2": "hello lucy",
}
keys = list(result.data.keys())
assert keys == ["name1", "hello1", "name2", "hello2"]
assert mock_load_fn.call_count == 1