Skip to content

Commit 00d6e20

Browse files
authored
Update cache-field-behavior.md (#6755)
The official documentation lacked an example and description of how to handle multiple parameters within the read() function when defining typePolicies. The proposed change addresses that by both showcasing that it is possible to handle multiple parameters and how to do so (using a syntax that was previously undocumented). I struggled for a while when it came to understanding how to handle this use case, so I am more than happy to share my findings while improving the docs with the hope of helping others that might find themselves in the same situation. 😃
1 parent 95c8a1a commit 00d6e20

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/source/caching/cache-field-behavior.mdx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,43 @@ const cache = new InMemoryCache({
7979
});
8080
```
8181

82+
If a field requires numerous parameters then each parameter must be wrapped in a variable that is then destructured and returned.
83+
Each parameter will be available as individual subfields.
84+
85+
The following `read` function assigns a default value of `UNKNOWN FIRST_NAME` to the `first_name` subfield of a `fullName` field and a `UNKNOWN LAST_NAME` to the `last_name` of a `fullName` field.
86+
87+
```ts
88+
const cache = new InMemoryCache({
89+
typePolicies: {
90+
Person: {
91+
fields: {
92+
fullName: {
93+
read(full_name = {
94+
first_name: "UNKNOWN FIRST_NAME",
95+
last_name: "UNKNOWN LAST_NAME",
96+
}) {
97+
return { ...full_name };
98+
},
99+
},
100+
},
101+
},
102+
},
103+
});
104+
```
105+
106+
The following `query` returns the `first_name` and `last_name` subfields from the `fullName` field:
107+
108+
```graphql
109+
query personWithFullName {
110+
fullName {
111+
first_name
112+
last_name
113+
}
114+
}
115+
```
116+
117+
If a field accepts arguments, the second parameter includes the values of those arguments. The following `read` function checks to see if the `maxLength` argument is provided when the `name` field is queried. If it is, the function returns only the first `maxLength` characters of the person's name. Otherwise, the person's full name is returned.
118+
82119
You can define a `read` function for a field that isn't even defined in your schema. For example, the following `read` function enables you to query a `userId` field that is always populated with locally stored data:
83120

84121
```ts

0 commit comments

Comments
 (0)