Skip to content

Commit f89ed6a

Browse files
committed
Adds support for resolving a union type when using a generated schema
1 parent b42a8ea commit f89ed6a

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

src/utilities/__tests__/buildASTSchema-test.js

+61
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,67 @@ describe('Schema Builder', () => {
394394
expect(output).to.equal(body);
395395
});
396396

397+
it('Specifying union type using __typename', async () => {
398+
const schema = buildSchema(`
399+
schema {
400+
query: Root
401+
}
402+
403+
type Root {
404+
fruits: [Fruit]
405+
}
406+
407+
union Fruit = Apple | Banana
408+
409+
type Apple {
410+
color: String
411+
}
412+
413+
type Banana {
414+
length: Int
415+
}
416+
`);
417+
418+
const query = `
419+
{
420+
fruits {
421+
... on Apple {
422+
color
423+
}
424+
... on Banana {
425+
length
426+
}
427+
}
428+
}
429+
`;
430+
431+
const root = {
432+
fruits: [
433+
{
434+
color: 'green',
435+
__typename: 'Apple',
436+
},
437+
{
438+
length: 5,
439+
__typename: 'Banana',
440+
}
441+
]
442+
};
443+
444+
expect(await graphql(schema, query, root)).to.deep.equal({
445+
data: {
446+
fruits: [
447+
{
448+
color: 'green',
449+
},
450+
{
451+
length: 5,
452+
}
453+
]
454+
}
455+
});
456+
});
457+
397458
it('Custom Scalar', () => {
398459
const body = dedent`
399460
schema {

src/utilities/buildASTSchema.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ export function buildASTSchema(ast: DocumentNode): GraphQLSchema {
437437
name: def.name.value,
438438
description: getDescription(def),
439439
types: def.types.map(t => produceObjectType(t)),
440-
resolveType: cannotExecuteSchema,
440+
resolveType: resolveUnionType,
441441
astNode: def,
442442
});
443443
}
@@ -530,6 +530,16 @@ function leadingSpaces(str) {
530530
return i;
531531
}
532532

533+
function resolveUnionType(result) {
534+
if (result && result.__typename) {
535+
return result.__typename;
536+
}
537+
throw new Error(
538+
'To resolve union types using a generated schema the result must have ' +
539+
'a __typename property corresponding to the exact type used.'
540+
);
541+
}
542+
533543
function cannotExecuteSchema() {
534544
throw new Error(
535545
'Generated Schema cannot use Interface or Union types for execution.'

0 commit comments

Comments
 (0)