GiraphQL
Search…
Unions

Defining Union Types

Union types are defined with a list of object types:
1
const builder = new SchemaBuilder<{
2
Objects: {
3
GiraffeStringFact: { factKind: 'string'; fact: string };
4
GiraffeNumericFact: { factKind: 'number'; fact: string; value: number };
5
};
6
}>({});
7
8
builder.objectType('GiraffeStringFact', {
9
fields: (t) => ({
10
fact: t.exposeString('fact', {}),
11
}),
12
});
13
14
const GiraffeNumericFact = builder.objectType('GiraffeNumericFact', {
15
fields: (t) => ({
16
fact: t.exposeString('fact', {}),
17
value: t.exposeFloat('value', {}),
18
}),
19
});
20
21
const GiraffeFact = builder.unionType('GiraffeFact', {
22
types: ['GiraffeStringFact', GiraffeNumericFact],
23
resolveType: (fact) => {
24
switch (fact.factKind) {
25
case 'number':
26
return GiraffeNumericFact;
27
case 'string':
28
return 'GiraffeStringFact';
29
}
30
},
31
});
Copied!
The types array can either contain Object type names defined in SchemaTypes, or and Object Ref created by object type. builder.objectType, builder.objectRef or other method, or a class that was used to implement an object type.
The resolveType function will be called with each item returned by a field that returns the unionType, and is used to determine which concrete the value corresponds to. It is usually good to have a shared property you can use to differentiate your union members.

Using Union Types

1
builder.queryField('giraffeFacts', (t) =>
2
t.field({
3
type: [GiraffeFact],
4
resolve: () => {
5
const fact1 = {
6
factKind: 'string',
7
fact: 'A giraffe’s spots are much like human fingerprints. No two individual giraffes have exactly the same pattern',
8
} as const;
9
10
const fact2 = {
11
factKind: 'number',
12
fact: 'Top speed (MPH)',
13
value: 35,
14
} as const;
15
16
return [fact1, fact2];
17
},
18
}),
19
);
Copied!
Last modified 4mo ago