Skip to content

Commit 6503fd6

Browse files
committed
Write about input unions
1 parent 577a9ad commit 6503fd6

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

website/pages/_meta.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const meta = {
1717
title: 'Advanced Guides',
1818
},
1919
'constructing-types': '',
20+
'input-unions': '',
2021
'defer-stream': '',
2122
'-- 3': {
2223
type: 'separator',

website/pages/input-unions.mdx

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
title: Input Unions
3+
---
4+
5+
import { Tabs } from 'nextra/components';
6+
7+
Some inputs will behave differently depending on what input we choose. Let's look at the case for
8+
a field named `product`, we can fetch a `Product` by either its `id` or its `name`. Currently we'd
9+
make a tradeoff for this by introducing two arguments that are both nullable, now if both are passed
10+
as null we'd have to handle that in code. To fix this the `@oneOf` directive was introduced so we
11+
can create these input-unions without sacrificing the strictly typed nature of our GraphQL Schema.
12+
13+
<Tabs items={['SDL', 'Code']}>
14+
<Tabs.Tab>
15+
```js
16+
const schema = buildSchema(`
17+
type Product {
18+
id: ID!
19+
name: String!
20+
}
21+
22+
input ProductInput @oneOf {
23+
id: ID
24+
name: String
25+
}
26+
27+
type Query {
28+
product(input: ProductInput!): Product
29+
}
30+
`);
31+
```
32+
</Tabs.Tab>
33+
<Tabs.Tab>
34+
```js
35+
const Product = new GraphQLObjectType({
36+
name: 'Product',
37+
fields: {
38+
id: {
39+
type: new GraphQLNonNull(GraphQLID),
40+
},
41+
name: {
42+
type: new GraphQLNonNull(GraphQLString),
43+
},
44+
},
45+
});
46+
47+
const ProductInput = new GraphQLInputObjectType({
48+
name: 'ProductInput',
49+
isOneOf: true,
50+
fields: {
51+
id: { type: GraphQLID },
52+
name: { type: GraphQLString },
53+
},
54+
});
55+
56+
const schema = new GraphQLSchema({
57+
query: new GraphQLObjectType({
58+
name: 'Query',
59+
fields: {
60+
product: {
61+
type: Product,
62+
args: { input: { type: ProductInput } },
63+
},
64+
},
65+
}),
66+
});
67+
```
68+
</Tabs.Tab>
69+
</Tabs>
70+
71+
It doesn't matter whether you have 2 or more inputs here, all that matters is
72+
that your user will have to specify one, and only one, for this input to be valid.

0 commit comments

Comments
 (0)