Typed queries, mutations and subscriptions over HTTP, Server-Sent Events or WebSockets, with middleware, pagination and batched lookups.
pyfect.graphql is a GraphQL client: an operation carries its printed document and the
schemas of its variables and result, and a client sends it through a transport and decodes
the answer. There is no GraphQL parser at runtime. It follows Effect's own
effect/graphql client, which does not use graphql-js either.
Operations and clients#
query(name, document=..., variables=..., result=...), mutation(...) and
subscription(...) declare operations; variables is left out for an operation without
any. A subclass of GraphQLGroup collects them as attributes, and client.make(Group)
gives an instance whose methods are typed by each operation: call group.repo_stars( variables) and get the decoded result. Each call also takes headers, url_params, a
per-call context, and partial=True, which gives a PartialResult with the data and
the errors instead of failing on GraphQL errors. A non-2xx HTTP response never succeeds,
even with partial=True: it is a ResponseError when its body has errors, and a
TransportError with the status, headers and Retry-After otherwise.
A failure is a GraphQLClientError naming the operation, with a reason:
ResponseError (the server's errors, the status and headers), TransportError,
EncodeError, DecodeError or PaginationError. is_retryable holds for a 429, a 5xx
or a valid Retry-After, and retry_after reads that header.
from typing import Any, TypedDict
import pyfect as fx
from pyfect import schema as S
from pyfect.graphql import GraphQLGroup, client, layer_http, query
from pyfect.graphql.client_error import ResponseError
from pyfect.http import router, server_response, uvicorn_server
class RepoVariables(TypedDict):
owner: str
name: str
class Repo(TypedDict):
stars: int
class RepoResult(TypedDict):
repository: Repo | None
# An operation is its printed document plus schemas for its variables and result.
RepoStars = query(
"RepoStars",
document="query RepoStars($owner: String!, $name: String!) "
"{ repository(owner: $owner, name: $name) { stars } }",
variables=S.Struct(RepoVariables),
result=S.Struct(RepoResult),
)
class GitHub(GraphQLGroup):
repo_stars = RepoStars
# A stand-in GraphQL server, so the example runs on its own.
class Body(TypedDict):
variables: RepoVariables
class Posted(TypedDict):
body: Body
@fx.fn
def answer():
request = yield from router.schema_json(S.Struct(Posted))
variables = request["body"]["variables"]
reply: dict[str, Any] = (
{"data": {"repository": {"stars": 13000}}}
if variables == {"owner": "Effect-TS", "name": "effect"}
else {"data": {"repository": None}, "errors": [{"message": "not found"}]}
)
return (yield from server_response.json(reply))
Server = router.use(lambda routes: routes.add("POST", "/graphql", answer()))
@fx.fn
def program():
github = yield from client.make(GitHub)
found = yield from github.repo_stars({"owner": "Effect-TS", "name": "effect"})
print(found)
# GraphQL errors fail the call, with the errors in its reason.
error = yield from github.repo_stars({"owner": "nobody", "name": "nothing"}).flip()
if isinstance(error.reason, ResponseError):
print(error.operation, [e["message"] for e in error.reason.errors], error.reason.status)
served = router.serve(Server, disable_logger=True, disable_listen_log=True)
transport = layer_http(url="/graphql") # sends with the HttpClient
fx.run_main(
program()
.pipe(fx.provide(transport))
.pipe(fx.provide(served))
.pipe(fx.provide(uvicorn_server.layer_test()))
)Transports#
layer_http(url=...) sends through the HTTP client: POST by default, or
GET for queries with query_method="GET". The URL is a string, an Effect, or a function
of the call's context and operation. Subscriptions use graphql-sse over the same URL, or a
graphql-transport-ws connection with web_socket=protocol.WebSocketOptions(...).
layer_web_socket(options) runs every operation over one shared graphql-transport-ws
connection, opened on the first call, with connection_params, keep-alive pings and an
idle timeout. Both WebSocket transports need a WebSocketConstructor, as in Effect: provide
pyfect.socket.ws.layer_web_socket_constructor (pyright reports it missing otherwise).
Subscriptions are streams, retried on retryable errors by
client.default_subscription_retry (or client.make(Group, subscription_retry=...)).
Middleware#
A subclass of GraphQLMiddleware[E, R] is a service tag. Declare a group as
GraphQLGroup[Auth], or attach one to an operation with .middleware(Auth), and the
client runs the middleware provided for it around each call, group middleware outermost.
A group whose operations bring their own middleware names it as its second type argument,
GraphQLGroup[Never, Auth], so that client.make requires it; leaving it out is a
TypeError when the class is made.
map_request(f) rewrites the request, adding a token for example, and its failures E
reach the caller; Implementation(execute=..., subscribe=...) wraps the whole call and
sees the transport's status.
Pagination and batching#
client.pages(group.issues, variables=..., connection=...) follows a Relay connection's
endCursor, sending it as $after until hasNextPage is false, as a stream of pages;
client.items streams their nodes. pyfect.graphql.resolver batches lookups like a
SQL resolver: ordered reads one item per
key by position (nodes(ids:)), find_by_id matches items by a key, and aliased
repeats an operation under aliases, up to 10 per request. ordered and find_by_id take
items=lambda data: data["search"]["nodes"], which picks the list out of the result and
gives the lookups its item type (Effect's path=("search", "nodes") also works, with
lookups typed Any). resolver.request(r)(key) is one lookup; lookups made together
become one request.
Testing#
client.make_test(Group, repo_stars=handler) gives a client whose operations call
handlers instead of a server, and client.layer_test(Tag, Group, ...) provides it through
a service tag. An operation without a handler dies with an UnimplementedError.
Reference: pyfect.graphql,
client,
operation,
protocol,
resolver.