Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active December 10, 2021 23:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/2de028b952c79d9a916ea31cdddef860 to your computer and use it in GitHub Desktop.
Save AndrewIngram/2de028b952c79d9a916ea31cdddef860 to your computer and use it in GitHub Desktop.
Strawberry Generic Connections (Python 3.10 syntax)
from typing import Generic, TypeVar
import strawberry
ConnectionNode = TypeVar("ConnectionNode")
@strawberry.type
class Edge(Generic[ConnectionNode]):
node: ConnectionNode
cursor: str
@strawberry.type
class PageInfo:
has_next_page: bool
has_previous_page: bool
start_cursor: str | None
end_cursor: str | None
EdgeType = TypeVar(name="EdgeType", bound=Edge)
@strawberry.type
class Connection(Generic[EdgeType]):
edges: list[EdgeType]
page_info: PageInfo
from .connections import Connection, ConnectionNode, Edge, PageInfo
from ..books import Book, ALL_BOOKS
from ..events import Event, ALL_EVENTS
@strawberry.field
def all_books(
first: int | None = None,
last: int | None = None,
before: str | None = None,
after: str | None = None,
) -> Connection[Edge[Book]]:
return Connection(
edges=[Edge(node=x, cursor='some-derived-cursor') for x in ALL_BOOKS],
page_info=PageInfo(
has_next_page=False,
has_previous_page=False,
start_cursor=None,
end_cursor=None,
),
)
@strawberry.type
class DistanceEdge(Edge[ConnectionNode]):
distance_km: float
@strawberry.field
def nearby_events(
first: int | None = None,
last: int | None = None,
before: str | None = None,
after: str | None = None,
near: LatLngInput,
) -> Connection[DistanceEdge[Event]]:
return Connection(
edges=[DistanceEdge(node=x, cursor='some-derived-cursor', distance=50.0) for x in ALL_EVENTS],
page_info=PageInfo(
has_next_page=False,
has_previous_page=False,
start_cursor=None,
end_cursor=None,
),
)
# Partial output of schema
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type BookEdge {
node: Book!
cursor: String!
}
type BookEdgeConnection {
edges: [BookEdge!]!
pageInfo: PageInfo!
}
type EventDistanceEdge {
node: Event!
cursor: String!
distanceKm: Float!
}
type EventDistanceEdgeConnection {
edges: [EventDistanceEdge!]!
pageInfo: PageInfo!
}
type Query {
allBooks(first: Int, last: Int, before: String, after: String): BookEdgeConnection!
nearbyEvents(first: Int, last: Int, before: String, after: String, near: LatLngInput!): EventDistanceEdgeConnection!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment