File: graphql_overview.py

package info (click to toggle)
python-apischema 0.18.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,608 kB
  • sloc: python: 15,266; sh: 7; makefile: 7
file content (91 lines) | stat: -rw-r--r-- 1,589 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from dataclasses import dataclass
from datetime import date, datetime
from typing import Collection
from uuid import UUID, uuid4

from graphql import graphql_sync, print_schema

from apischema.graphql import graphql_schema, resolver


@dataclass
class User:
    id: UUID
    username: str
    birthday: date | None = None

    @resolver
    def posts(self) -> Collection["Post"]:
        return [post for post in POSTS if post.author.id == self.id]


@dataclass
class Post:
    id: UUID
    author: User
    date: datetime
    content: str


USERS = [User(uuid4(), "foo"), User(uuid4(), "bar")]
POSTS = [Post(uuid4(), USERS[0], datetime.now(), "Hello world!")]


def users() -> Collection[User]:
    return USERS


def posts() -> Collection[Post]:
    return POSTS


def user(username: str) -> User | None:
    for user in users():
        if user.username == username:
            return user
    else:
        return None


schema = graphql_schema(query=[users, user, posts], id_types={UUID})
schema_str = """\
type Query {
  users: [User!]!
  user(username: String!): User
  posts: [Post!]!
}

type User {
  id: ID!
  username: String!
  birthday: Date
  posts: [Post!]!
}

scalar Date

type Post {
  id: ID!
  author: User!
  date: Datetime!
  content: String!
}

scalar Datetime"""
assert print_schema(schema) == schema_str

query = """
{
  users {
    username
    posts {
        content
    }
  }
}"""
assert graphql_sync(schema, query).data == {
    "users": [
        {"username": "foo", "posts": [{"content": "Hello world!"}]},
        {"username": "bar", "posts": []},
    ]
}