Skip to content

Commit

Permalink
Add more types, use cases and examples
Browse files Browse the repository at this point in the history
  • Loading branch information
rafalp committed Oct 7, 2024
1 parent 1d2f200 commit 6de609c
Show file tree
Hide file tree
Showing 22 changed files with 372 additions and 42 deletions.
11 changes: 10 additions & 1 deletion example/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
from ariadne.asgi import GraphQL
from ariadne.asgi.handlers import GraphQLTransportWSHandler
from starlette.middleware.cors import CORSMiddleware

from .schema import schema


app = GraphQL(schema, debug=True)
app = CORSMiddleware(
GraphQL(
schema,
debug=True,
websocket_handler=GraphQLTransportWSHandler(),
),
allow_origins="*",
)
15 changes: 9 additions & 6 deletions example/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@

class DataBase:
_data: dict[str, dict[int, Any]]
_id: int
_id: dict[str, int]

def __init__(self, data: dict[str, dict[int, Any]], counter: int = 0):
def __init__(self, data: dict[str, dict[int, Any]]):
self._data = data
self._id = counter
self._id = {}

for table_name, table_data in data.items():
self._id[table_name] = max(list(table_data))

async def get_row(self, table: str, **kwargs) -> Any:
assert kwargs, "use kwargs to filter"
Expand Down Expand Up @@ -40,8 +43,8 @@ async def get_all(self, table: str, **kwargs) -> list[Any]:
async def insert(self, table: str, obj: Any):
assert obj.id is None, "obj.id attr must be None"

self._id += 1
obj.id = self._id
self._id[table] += 1
obj.id = self._id[table]

self._data[table][obj.id] = obj

Expand All @@ -52,4 +55,4 @@ async def delete(self, table: str, id: int):
self._data[table].pop(id, None)


db = DataBase(get_data(), 1000)
db = DataBase(get_data())
75 changes: 49 additions & 26 deletions example/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,12 @@

from .models.category import Category
from .models.group import Group
from .models.post import Post
from .models.user import User


def get_data() -> dict[str, dict[int, Any]]:
return {
"categories": {
1: Category(
id=1,
name="First category",
parent_id=None,
),
2: Category(
id=2,
name="Second category",
parent_id=None,
),
3: Category(
id=3,
name="Child category",
parent_id=1,
),
4: Category(
id=4,
name="Other child category",
parent_id=1,
),
},
"groups": {
1: Group(
id=1,
Expand All @@ -45,26 +24,70 @@ def get_data() -> dict[str, dict[int, Any]]:
1: User(
id=1,
username="JohnDoe",
email="[email protected]",
group_id=1,
),
2: User(
id=2,
username="Alice",
email="[email protected]",
group_id=1,
),
3: User(
id=3,
username="Bob",
email="[email protected]",
group_id=2,
),
4: User(
id=4,
username="Mia",
email="[email protected]",
group_id=2,
),
},
"categories": {
1: Category(
id=1,
name="First category",
parent_id=None,
),
2: Category(
id=2,
name="Second category",
parent_id=None,
),
3: Category(
id=3,
name="Child category",
parent_id=1,
),
4: Category(
id=4,
name="Other child category",
parent_id=1,
),
},
"posts": {
1: Post(
id=1,
message="Lorem ipsum",
category_id=1,
poster_id=1,
),
2: Post(
id=2,
message="Dolor met",
category_id=2,
poster_id=2,
),
3: Post(
id=3,
message="Sit amet",
category_id=3,
poster_id=3,
),
4: Post(
id=4,
message="Elit",
category_id=4,
poster_id=4,
),
},
}
9 changes: 9 additions & 0 deletions example/models/post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from dataclasses import dataclass


@dataclass
class Post:
id: int
message: str
category_id: int | None
poster_id: int | None
1 change: 0 additions & 1 deletion example/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@
class User:
id: int
username: str
email: str
group_id: int
4 changes: 3 additions & 1 deletion example/queries/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import Any

from . import categories, groups, hello, users
from . import calendar, categories, groups, hello, posts, users

queries: Any = [
calendar.Query,
categories.Query,
groups.Query,
hello.Query,
posts.Query,
users.Query,
]
20 changes: 20 additions & 0 deletions example/queries/calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from datetime import datetime

from ariadne_graphql_modules import GraphQLObject
from graphql import GraphQLResolveInfo

from ..database import db
from ..scalars.date import DateScalar
from ..scalars.datetime import DateTimeScalar


class Query(GraphQLObject):
@GraphQLObject.field()
@staticmethod
async def date(obj, info: GraphQLResolveInfo) -> DateScalar:
return DateScalar(datetime.now().date())

@GraphQLObject.field()
@staticmethod
async def datetime(obj, info: GraphQLResolveInfo) -> DateTimeScalar:
return DateTimeScalar(datetime.now())
6 changes: 4 additions & 2 deletions example/queries/categories.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ariadne_graphql_modules import GraphQLObject
from ariadne_graphql_modules import GraphQLID, GraphQLObject
from graphql import GraphQLResolveInfo

from ..database import db
Expand All @@ -13,7 +13,9 @@ async def categories(obj, info: GraphQLResolveInfo) -> list[CategoryType]:

@GraphQLObject.field()
@staticmethod
async def category(obj, info: GraphQLResolveInfo, id: str) -> CategoryType | None:
async def category(
obj, info: GraphQLResolveInfo, id: GraphQLID
) -> CategoryType | None:
try:
id_int = int(id)
except (TypeError, ValueError):
Expand Down
4 changes: 2 additions & 2 deletions example/queries/groups.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ariadne_graphql_modules import GraphQLObject
from ariadne_graphql_modules import GraphQLID, GraphQLObject
from graphql import GraphQLResolveInfo

from ..database import db
Expand All @@ -22,7 +22,7 @@ async def groups(

@GraphQLObject.field()
@staticmethod
async def group(obj, info: GraphQLResolveInfo, id: str) -> GroupType | None:
async def group(obj, info: GraphQLResolveInfo, id: GraphQLID) -> GroupType | None:
try:
id_int = int(id)
except (TypeError, ValueError):
Expand Down
25 changes: 25 additions & 0 deletions example/queries/posts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import Optional

from ariadne_graphql_modules import GraphQLID, GraphQLObject
from graphql import GraphQLResolveInfo

from ..database import db
from ..models.post import Post
from ..types.post import PostType


class Query(GraphQLObject):
@GraphQLObject.field(graphql_type=list[PostType])
@staticmethod
async def posts(obj, info: GraphQLResolveInfo) -> list[Post]:
return await db.get_all("posts")

@GraphQLObject.field(graphql_type=Optional[PostType])
@staticmethod
async def post(obj, info: GraphQLResolveInfo, id: GraphQLID) -> Post | None:
try:
id_int = int(id)
except (TypeError, ValueError):
return None

return await db.get_row("posts", id=id_int)
12 changes: 11 additions & 1 deletion example/queries/users.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ariadne_graphql_modules import GraphQLObject
from ariadne_graphql_modules import GraphQLID, GraphQLObject
from graphql import GraphQLResolveInfo

from ..database import db
Expand All @@ -10,3 +10,13 @@ class Query(GraphQLObject):
@staticmethod
async def users(obj, info: GraphQLResolveInfo) -> list[UserType]:
return await db.get_all("users")

@GraphQLObject.field()
@staticmethod
async def user(obj, info: GraphQLResolveInfo, id: GraphQLID) -> UserType | None:
try:
id_int = int(id)
except (TypeError, ValueError):
return None

return await db.get_row("users", id=id_int)
Empty file added example/scalars/__init__.py
Empty file.
17 changes: 17 additions & 0 deletions example/scalars/date.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from datetime import date, datetime
from typing import Union, cast

from ariadne_graphql_modules import GraphQLScalar


class DateScalar(GraphQLScalar):
@classmethod
def serialize(cls, value: Union["DateScalar", date]) -> str:
if isinstance(value, cls):
value = cast(date, value.unwrap())

return value.strftime("%Y-%m-%d")

@classmethod
def parse_value(cls, value: str) -> date:
return datetime.strptime("%Y-%m-%d").date()
17 changes: 17 additions & 0 deletions example/scalars/datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from datetime import datetime
from typing import Union, cast

from ariadne_graphql_modules import GraphQLScalar


class DateTimeScalar(GraphQLScalar):
@classmethod
def serialize(cls, value: Union["DateTimeScalar", datetime]) -> str:
if isinstance(value, cls):
value = cast(datetime, value.unwrap())

return value.isoformat()

@classmethod
def parse_value(cls, value: str) -> datetime:
return datetime.fromisoformat(value)
7 changes: 6 additions & 1 deletion example/schema.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from ariadne_graphql_modules import make_executable_schema

from .queries import queries
from .subscriptions import subscriptions


schema = make_executable_schema(queries, convert_names_case=True)
schema = make_executable_schema(
queries,
subscriptions,
convert_names_case=True,
)
5 changes: 5 additions & 0 deletions example/subscriptions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from typing import Any

from . import events

subscriptions: Any = [events.Subscription]
26 changes: 26 additions & 0 deletions example/subscriptions/events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import random
from asyncio import sleep
from typing import AsyncGenerator
from datetime import datetime

from ariadne_graphql_modules import GraphQLSubscription
from graphql import GraphQLResolveInfo

from ..types.event import EventType


class Subscription(GraphQLSubscription):
event: EventType

@GraphQLSubscription.source("event")
async def source_event(obj, info: GraphQLResolveInfo) -> AsyncGenerator[int, None]:
i = 0

while True:
i += 1
yield i
await sleep(float(random.randint(1, 50)) / 10)

@GraphQLSubscription.resolver("event")
async def resolve_event(obj: int, info: GraphQLResolveInfo) -> dict:
return {"id": obj, "payload": datetime.now()}
Loading

0 comments on commit 6de609c

Please sign in to comment.