File tree 2 files changed +72
-1
lines changed
2 files changed +72
-1
lines changed Original file line number Diff line number Diff line change @@ -394,6 +394,67 @@ describe('Schema Builder', () => {
394
394
expect ( output ) . to . equal ( body ) ;
395
395
} ) ;
396
396
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
+
397
458
it ( 'Custom Scalar' , ( ) => {
398
459
const body = dedent `
399
460
schema {
Original file line number Diff line number Diff line change @@ -437,7 +437,7 @@ export function buildASTSchema(ast: DocumentNode): GraphQLSchema {
437
437
name : def . name . value ,
438
438
description : getDescription ( def ) ,
439
439
types : def . types . map ( t => produceObjectType ( t ) ) ,
440
- resolveType : cannotExecuteSchema ,
440
+ resolveType : resolveUnionType ,
441
441
astNode : def ,
442
442
} ) ;
443
443
}
@@ -530,6 +530,16 @@ function leadingSpaces(str) {
530
530
return i ;
531
531
}
532
532
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
+
533
543
function cannotExecuteSchema ( ) {
534
544
throw new Error (
535
545
'Generated Schema cannot use Interface or Union types for execution.'
You can’t perform that action at this time.
0 commit comments