File: generics.md

package info (click to toggle)
strawberry-graphql 0.306.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 18,176 kB
  • sloc: javascript: 178,052; python: 65,643; sh: 33; makefile: 25
file content (245 lines) | stat: -rw-r--r-- 4,004 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
---
title: Generics
---

# Generics

Strawberry supports using Python's `Generic` typing to dynamically create
reusable types.

Strawberry will automatically generate the correct GraphQL schema from the
combination of the generic type and the type arguments. Generics are supported
in Object types, Input types, and Arguments to queries, mutations, and scalars.

Let's take a look at an example:

# Object Types

```python
from typing import Generic, List, TypeVar

import strawberry

T = TypeVar("T")


@strawberry.type
class Page(Generic[T]):
    number: int
    items: List[T]
```

This example defines a generic type `Page` that can be used to represent a page
of any type. For example, we can create a page of `User` objects:

<CodeGrid>

```python
import strawberry


@strawberry.type
class User:
    name: str


@strawberry.type
class Query:
    users: Page[User]
```

```graphql
type Query {
  users: UserPage!
}

type User {
  name: String!
}

type UserPage {
  number: Int!
  items: [User!]!
}
```

</CodeGrid>

It is also possible to use a specialized generic type directly. For example, the
same example above could be written like this:

<CodeGrid>

```python
import strawberry


@strawberry.type
class User:
    name: str


@strawberry.type
class UserPage(Page[User]): ...


@strawberry.type
class Query:
    users: UserPage
```

```graphql
type Query {
  users: UserPage!
}

type User {
  name: String!
}

type UserPage {
  number: Int!
  items: [User!]!
}
```

</CodeGrid>

# Input and Argument Types

Arguments to queries and mutations can also be made generic by creating Generic
Input types. Here we'll define an input type that can serve as a collection of
anything, then create a specialization by using as a filled-in argument on a
mutation.

<CodeGrid>

```python
import strawberry
from typing import Generic, List, Optional, TypeVar

T = TypeVar("T")


@strawberry.input
class CollectionInput(Generic[T]):
    values: List[T]


@strawberry.input
class PostInput:
    name: str


@strawberry.type
class Post:
    id: int
    name: str


@strawberry.type
class Mutation:
    @strawberry.mutation
    def add_posts(self, posts: CollectionInput[PostInput]) -> bool:
        return True


@strawberry.type
class Query:
    most_recent_post: Optional[Post] = None


schema = strawberry.Schema(query=Query, mutation=Mutation)
```

```graphql
input PostInputCollectionInput {
  values: [PostInput!]!
}

input PostInput {
  name: String!
}

type Post {
  id: Int!
  name: String!
}

type Query {
  mostRecentPost: Post
}

type Mutation {
  addPosts(posts: PostInputCollectionInput!): Boolean!
}
```

</CodeGrid>

> **Note**: Pay attention to the fact that both `CollectionInput` and
> `PostInput` are Input types. Providing `posts: CollectionInput[Post]` to
> `add_posts` (i.e. using the non-input `Post` type) would have resulted in an
> error:
>
> ```
> PostCollectionInput fields cannot be resolved. Input field type must be a
> GraphQL input type
> ```

# Multiple Specializations

Using multiple specializations of a Generic type will work as expected. Here we
define a `Point2D` type and then specialize it for both `int`s and `float`s.

<CodeGrid>

```python
from typing import Generic, TypeVar

import strawberry

T = TypeVar("T")


@strawberry.input
class Point2D(Generic[T]):
    x: T
    y: T


@strawberry.type
class Mutation:
    @strawberry.mutation
    def store_line_float(self, a: Point2D[float], b: Point2D[float]) -> bool:
        return True

    @strawberry.mutation
    def store_line_int(self, a: Point2D[int], b: Point2D[int]) -> bool:
        return True
```

```graphql
type Mutation {
  storeLineFloat(a: FloatPoint2D!, b: FloatPoint2D!): Boolean!
  storeLineInt(a: IntPoint2D!, b: IntPoint2D!): Boolean!
}

input FloatPoint2D {
  x: Float!
  y: Float!
}

input IntPoint2D {
  x: Int!
  y: Int!
}
```

</CodeGrid>

# Variadic Generics

Variadic Generics, introduced in [PEP-646][pep-646], are currently unsupported.

[pep-646]: https://peps.python.org/pep-0646/