Skip to content

Commit 511e2df

Browse files
committed
Adds support for providing the type of an object when the type is a union
1 parent 62d1121 commit 511e2df

File tree

2 files changed

+72
-3
lines changed

2 files changed

+72
-3
lines changed

src/execution/execute.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,9 +1034,17 @@ function completeAbstractValue(
10341034
path: ResponsePath,
10351035
result: mixed
10361036
): mixed {
1037-
const runtimeType = returnType.resolveType ?
1038-
returnType.resolveType(result, exeContext.contextValue, info) :
1039-
defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);
1037+
let runtimeType;
1038+
1039+
if (result && result.__type) {
1040+
runtimeType = result.__type;
1041+
} else if (returnType.resolveType) {
1042+
runtimeType = returnType.resolveType(result, exeContext.contextValue, info);
1043+
} else {
1044+
runtimeType = defaultResolveTypeFn(
1045+
result, exeContext.contextValue, info, returnType
1046+
);
1047+
}
10401048
10411049
const promise = getPromise(runtimeType);
10421050
if (promise) {

src/utilities/__tests__/buildASTSchema-test.js

Lines changed: 61 additions & 0 deletions
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 which type to use for union types using __type', 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+
__type: 'Apple',
436+
},
437+
{
438+
length: 5,
439+
__type: '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 {

0 commit comments

Comments
 (0)