stitch
stitch copied to clipboard
Proposal: Use schema merging instead of federation
Now we use some kind of patched Apollo federation mechanism to unite all schemas from resource group and load the result schema to Gateway. But actually, it isn't real federation of graphql services because we have only one. If we will have another one we won't be able to add it using standard Apollo federation mechanism without major changes.
The major issue that custom type-system directives aren't supported in schema federation. So the patch handles it and the code is a bit complex.
We can use schema merging mechanism from graphql-tools.
Code example:
interface Schema {
metadata: {
namespace: string;
name: string;
dependencies?: Array<{
namespace: string;
name: string;
}>;
};
schema: string;
}
const schemas: Schema[] = [
{
metadata: {
namespace: 'my-namespace',
name: 'my-schema',
},
schema: `
type Query {
foo: Foo!
}
type Foo {
field1: String
}
`,
},
{
metadata: {
namespace: 'other-namespace',
name: 'other-schema',
dependencies: [{
namespace: 'my-namespace',
name: 'my-schema'
}],
},
schema: `
type Query {
bar: Bar!
}
type Bar {
foo: Foo
}
`,
}
];
const prepareDependency = (dep: DocumentNode) =>
dep.definitions.filter(d => {
if (d.kind !== Kind.OBJECT_TYPE_DEFINITION) return true;
const od = d as ObjectTypeDefinitionNode;
return od.name.value !== 'Query' && od.name.value !== 'Mutation' && od.name.value !== 'Subscription';
});
const resolveDependencies = (schema: Schema, schemas: Schema[]) =>
schema.metadata.dependencies
?.map(d => schemas.find(s => s.metadata.namespace === d.namespace && s.metadata.name === d.name))
.map(d => parse(d.schema))
.map(prepareDependency)
.flat() ?? [];
const schemas = schemas.map(us =>
buildSchemaFromTypeDefinitions([us.schema, baseSchema, ...resolveDependencies(us, schemas)]),
);
const schema = mergeSchemas({ schemas, schemaDirectives });
Here is the whole file.
I think it's a property of the state (mutability), not the the dispatcher