Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand extended interface selections for subservice compatibility #1912

Merged
merged 6 commits into from
Aug 17, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
88 changes: 69 additions & 19 deletions packages/delegate/src/transforms/ExpandAbstractTypes.ts
Expand Up @@ -10,6 +10,7 @@ import {
TypeInfo,
getNamedType,
isAbstractType,
isInterfaceType,
visit,
visitWithTypeInfo,
} from 'graphql';
Expand All @@ -23,7 +24,9 @@ export default class ExpandAbstractTypes implements Transform {

constructor(sourceSchema: GraphQLSchema, targetSchema: GraphQLSchema) {
this.targetSchema = targetSchema;
this.mapping = extractPossibleTypes(sourceSchema, targetSchema);
const { mapping, interfaceExtensions } = extractPossibleTypes(sourceSchema, targetSchema);
this.mapping = mapping;
this.interfaceExtensions = interfaceExtensions;
this.reverseMapping = flipMapping(this.mapping);
}

Expand All @@ -32,8 +35,10 @@ export default class ExpandAbstractTypes implements Transform {
this.targetSchema,
this.mapping,
this.reverseMapping,
this.interfaceExtensions,
originalRequest.document
);

return {
...originalRequest,
document,
Expand All @@ -44,17 +49,29 @@ export default class ExpandAbstractTypes implements Transform {
function extractPossibleTypes(sourceSchema: GraphQLSchema, targetSchema: GraphQLSchema) {
const typeMap = sourceSchema.getTypeMap();
const mapping: Record<string, Array<string>> = Object.create(null);
const interfaceExtensions: Record<string, Record<string, boolean>> = Object.create(null);
Object.keys(typeMap).forEach(typeName => {
const type = typeMap[typeName];
if (isAbstractType(type)) {
const targetType = targetSchema.getType(typeName);
if (!isAbstractType(targetType)) {

if (isInterfaceType(type) && isInterfaceType(targetType)) {
const targetTypeFields = Object.keys(targetType.getFields());
const extensionFields = Object.keys(type.getFields()).filter(
(fieldName: string) => !targetTypeFields.includes(fieldName)
);
if (extensionFields.length) {
interfaceExtensions[typeName] = extensionFields;
}
}

if (!isAbstractType(targetType) || typeName in interfaceExtensions) {
const implementations = sourceSchema.getPossibleTypes(type);
mapping[typeName] = implementations.filter(impl => targetSchema.getType(impl.name)).map(impl => impl.name);
}
}
});
return mapping;
return { mapping, interfaceExtensions };
}

function flipMapping(mapping: Record<string, Array<string>>): Record<string, Array<string>> {
Expand All @@ -75,11 +92,13 @@ function expandAbstractTypes(
targetSchema: GraphQLSchema,
mapping: Record<string, Array<string>>,
reverseMapping: Record<string, Array<string>>,
gmac marked this conversation as resolved.
Show resolved Hide resolved
interfaceExtensions: Record<string, Array<string>>,
document: DocumentNode
): DocumentNode {
const operations: Array<OperationDefinitionNode> = document.definitions.filter(
def => def.kind === Kind.OPERATION_DEFINITION
) as Array<OperationDefinitionNode>;

const fragments: Array<FragmentDefinitionNode> = document.definitions.filter(
def => def.kind === Kind.FRAGMENT_DEFINITION
) as Array<FragmentDefinitionNode>;
Expand All @@ -94,6 +113,19 @@ function expandAbstractTypes(
} while (existingFragmentNames.indexOf(fragmentName) !== -1);
return fragmentName;
};
const generateInlineFragment = (typeName: string, selectionSet: SelectionSetNode) => {
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: typeName,
},
},
selectionSet,
};
};

const newFragments: Array<FragmentDefinitionNode> = [];
const fragmentReplacements: Record<string, Array<{ fragmentName: string; typeName: string }>> = Object.create(null);
Expand Down Expand Up @@ -140,10 +172,13 @@ function expandAbstractTypes(
newDocument,
visitWithTypeInfo(typeInfo, {
[Kind.SELECTION_SET](node: SelectionSetNode) {
const newSelections = [...node.selections];
let newSelections = node.selections;
const addedSelections = [];
const maybeType = typeInfo.getParentType();
if (maybeType != null) {
const parentType: GraphQLNamedType = getNamedType(maybeType);
const extendedInterface = interfaceExtensions[parentType.name];
const extendedInterfaceFields = [];
node.selections.forEach((selection: SelectionNode) => {
if (selection.kind === Kind.INLINE_FRAGMENT) {
if (selection.typeCondition != null) {
Expand All @@ -155,17 +190,7 @@ function expandAbstractTypes(
maybePossibleType != null &&
implementsAbstractType(targetSchema, parentType, maybePossibleType)
) {
newSelections.push({
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: possibleType,
},
},
selectionSet: selection.selectionSet,
});
addedSelections.push(generateInlineFragment(possibleType, selection.selectionSet));
}
});
}
Expand All @@ -177,7 +202,7 @@ function expandAbstractTypes(
const typeName = replacement.typeName;
const maybeReplacementType = targetSchema.getType(typeName);
if (maybeReplacementType != null && implementsAbstractType(targetSchema, parentType, maybeType)) {
newSelections.push({
addedSelections.push({
kind: Kind.FRAGMENT_SPREAD,
name: {
kind: Kind.NAME,
Expand All @@ -187,24 +212,49 @@ function expandAbstractTypes(
}
});
}
} else if (
selection.kind === Kind.FIELD &&
extendedInterface != null &&
extendedInterface.includes(selection.name.value)
gmac marked this conversation as resolved.
Show resolved Hide resolved
) {
extendedInterfaceFields.push(selection);
}
});

if (parentType.name in reverseMapping) {
newSelections.push({
addedSelections.push({
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: '__typename',
},
});
}

if (extendedInterfaceFields.length) {
const possibleTypes = mapping[parentType.name];
if (possibleTypes != null) {
possibleTypes.forEach(possibleType => {
addedSelections.push(
generateInlineFragment(possibleType, {
kind: Kind.SELECTION_SET,
selections: extendedInterfaceFields,
})
);
});

newSelections = newSelections.filter(
(selection: SelectionNode) =>
selection.kind !== Kind.FIELD || !extendedInterface.includes(selection.name.value)
);
}
}
}

if (newSelections.length !== node.selections.length) {
if (addedSelections.length) {
return {
...node,
selections: newSelections,
selections: newSelections.concat(addedSelections),
};
}
},
Expand Down
51 changes: 51 additions & 0 deletions packages/stitch/tests/extendedInterface.test.ts
@@ -0,0 +1,51 @@
import { graphql } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { stitchSchemas } from '../src/stitchSchemas';

describe('extended interfaces', () => {
test('expands extended interface types for subservices', async () => {
const itemsSchema = makeExecutableSchema({
typeDefs: `
interface Slot {
id: ID!
}
type Item implements Slot {
id: ID!
name: String!
}
type Query {
slot: Slot
}
`,
resolvers: {
Query: {
slot(obj, args, context, info) {
return { __typename: 'Item', id: '23', name: 'The Item' };
}
}
}
});

const stitchedSchema = stitchSchemas({
subschemas: [
{ schema: itemsSchema },
],
typeDefs: `
extend interface Slot {
name: String!
}
`,
});

const { data } = await graphql(stitchedSchema, `
query {
slot {
id
name
}
}
`);

expect(data.slot).toEqual({ id: '23', name: 'The Item' });
});
});