File: private.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 (82 lines) | stat: -rw-r--r-- 1,701 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
---
title: Private Fields
---

# Private Fields

Private (external) fields can provide local context for later resolution. These
fields will act as plain fields so will not be exposed in the GraphQL API.

Some uses include:

- Context that relies upon field inputs.
- Avoiding fully materializing an object hierarchy (lazy resolution)

# Defining a private field

Specifying a field with `strawberry.Private[...]` will desigate it as internal
and not for GraphQL.

# Example

Consider the following type, which can accept any Python object and handle
converting it to string, representation, or templated output:

```python
@strawberry.type
class Stringable:
    value: strawberry.Private[object]

    @strawberry.field
    def string(self) -> str:
        return str(self.value)

    @strawberry.field
    def repr(self) -> str:
        return repr(self.value)

    @strawberry.field
    def format(self, template: str) -> str:
        return template.format(my=self.value)
```

The `Private[...]` type lets Strawberry know that this field is not a GraphQL
field. "value" is a regular field on the class, but it is not exposed on the
GraphQL API.

```python
@strawberry.type
class Query:
    @strawberry.field
    def now(self) -> Stringable:
        return Stringable(value=datetime.datetime.now())
```

Queries can then select the fields and formats desired, but formatting only
happens as requested:

<CodeGrid>

```graphql
{
  now {
    format(template: "{my.year}")
    string
    repr
  }
}
```

```json
{
  "data": {
    "now": {
      "format": "2022",
      "string": "2022-09-03 17:03:04.923068",
      "repr": "datetime.datetime(2022, 9, 3, 17, 3, 4, 923068)"
    }
  }
}
```

</CodeGrid>