Skip to content

Commit 620e7a6

Browse files
captbaritonefacebook-github-bot
authored andcommitted
Document resolvers returning abstract types
Reviewed By: gordyf Differential Revision: D66987887 fbshipit-source-id: f9c32ba35dbc360682839507bf69533bd549b2a7
1 parent 4c90b64 commit 620e7a6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

website/docs/guides/relay-resolvers/return-types.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,38 @@ function Post() {
109109
}
110110
```
111111

112+
## Abstract Types
113+
114+
Resolvers may return some permutations of "abstract" types (GraphQL unions and interfaces). To use this feature simply use the abstract type's name in the docblock field description and include the typename in the object returned from your resolver. For "strong" types, that will look like: `{id: DataID, __typename: string}`. For "weak" types that will look like: `{__relay_model_instance: T, __typename: string}`.
115+
116+
```tsx
117+
import {DataID} from 'relay-runtime';
118+
119+
type AnimalTypenames = "Cat" | "Dog";
120+
/**
121+
* @RelayResolver User.pet: Animal
122+
*/
123+
export function pet(user: User): {id: DataID, __typename: AnimalTypenames } {
124+
return {id: "5", __typename: "Dog" }
125+
}
126+
```
127+
128+
:::tip
129+
Relay will generate type assertions to ensure your resolver function returns the expected type. However, not all combinations are supported. For example, Relay does not yet support the following permutations of abstract types: Unions including weak types, abstract types which mix strong add weak types, and abstract types which include server-backed types.
130+
:::
131+
132+
While abstract types themselves cannot be defined using Resolver syntax today, you may define interfaces and unions, as well as their members, using [Client Schema Extensions](../client-schema-extensions.md). For example:
133+
134+
```graphql title="client-schema.graphql"
135+
interface Animal {
136+
legs: Int
137+
}
138+
139+
extend type Cat implements Animal {
140+
__do_not_use: String # Placeholder because GraphQL does not allow empty field sets.
141+
}
142+
```
143+
112144
## JavaScript Values
113145

114146
There are rare cases where you want to return an arbitrary JavaScript value from your Resolver schema, one which cannot not have a corresponding GraphQL type. As an escape hatch Relay supports a custom return type `RelayResolverValue` that allows you to return any JavaScript value from your resolver. **JavaScript values returned from resolvers should be immutable.**

0 commit comments

Comments
 (0)