Working with Schema Stitching
1. Understanding Schema Composition
| Approach | Use |
|---|---|
| Schema stitching | Merge schemas from independent services into one |
| Federation | Subgraphs declare entities + ownership; gateway plans queries |
| Modular monolith | Single schema split across files in one process |
2. Merging Type Definitions
Example: stitchSchemas
import { stitchSchemas } from "@graphql-tools/stitch";
const gateway = stitchSchemas({
subschemas: [
{ schema: usersSchema, executor: usersExecutor },
{ schema: ordersSchema, executor: ordersExecutor }
]
});
3. Delegating to Subschemas
Example: delegateToSchema
import { delegateToSchema } from "@graphql-tools/delegate";
resolvers: {
Order: {
customer: (order, _, ctx, info) => delegateToSchema({
schema: usersSubschema, operation: "query",
fieldName: "user", args: { id: order.customerId }, context: ctx, info
})
}
}
4. Transforming Schemas
| Transform | Use |
|---|---|
| RenameTypes | Resolve naming clashes |
| RenameRootFields | Namespace by service |
| FilterTypes | Hide internal types |
| WrapType | Add wrapping fields/connections |
5. Handling Type Conflicts
| Strategy | Detail |
|---|---|
| Rename | Prefix conflicting types per subschema |
| Merge | Combine fields from multiple sources |
| Resolve last | Last subschema wins |
6. Implementing Type Extensions
7. Forwarding Context
| Concern | Detail |
|---|---|
| Auth headers | Forward Authorization to subschemas |
| Tracing | Propagate traceparent (W3C) |
| Locale | Pass Accept-Language |
8. Batching Delegated Queries
| Mechanism | Detail |
|---|---|
| batchDelegateToSchema | Group sibling delegations |
| DataLoader at gateway | Avoid N+1 across subschemas |
| Batched executor | Send array of operations downstream |
9. Handling Errors in Stitching
| Source | Behavior |
|---|---|
| Subschema error | Propagated with adjusted path |
| Network failure | Catch in executor, return GraphQLError |
| Partial result | Other subschemas still resolve |
10. Testing Stitched Schema
| Test | Detail |
|---|---|
| Cross-service query | Verify combined data |
| Subschema mock | Replace executor with mock |
| Schema validity | Lint after stitching |