pattern/api/graphql-federation
- Apollo Subgraph
- Bun
- ElysiaJS
- Federation Composition
- GraphQL Yoga
- Hive Gateway
- TypeScript
- graphql-js
Vários serviços GraphQL donos dos próprios tipos publicados como um supergraph; o gateway resolve a entidade no dono e os campos extras em quem a estende.
pattern/api/graphql-federation
Cenário
Contas é dono de Account; transações é dono de Transaction e estende Account.transactions. Uma query traz contas com extrato.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Vários serviços GraphQL donos dos próprios tipos publicados como um supergraph
Esconde cada passo: lembre antes de tocar para revelar.
accounts: type Account @key(fields: "id") e __resolveReference
transactions estende Account pela mesma chave
Composição escrita à mão lê o SDL de { _service { sdl } } e mapeia cada campo ao seu subgraph; campo fora da chave em dois subgraphs falha
O gateway planejaLista no dono com a chave id, um _entities no contribuidor, junção pela posição
Trade-offs
O que se ganha, o que se paga
Vantagens
Um schema e uma query por tela
Deploy independente por subgraph
Custos
Gateway e composição para operar
Com menos de três serviços não compensa
Código
pattern/api/graphql-federation
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: composição com cada campo no seu subgraph; accounts recebe { accounts { id holderName balanceCents } }, transactions recebe um _entities com 2 contas; o cliente recebe Ana com 2 transações e Carlos com 1, sem o id que ele não pediu.
Código
src/demo.ts// Demo: one GraphQL query answered by two independently owned subgraphs, joined by the gateway over the supergraph.
import { type GraphQLResolverMap, buildSubgraphSchema } from "@apollo/subgraph";
import { Elysia } from "elysia";
import { type DocumentNode, type FieldNode, Kind, type TypeNode, parse, print } from "graphql";
import { createYoga } from "graphql-yoga";
const ACCOUNTS_PORT = Number(Bun.env.GRAPHQL_FEDERATION_ACCOUNTS_PORT ?? 4050);
const TRANSACTIONS_PORT = Number(Bun.env.GRAPHQL_FEDERATION_TRANSACTIONS_PORT ?? 4051);
// Subgraph side only: @apollo/subgraph answers _service and _entities; composition and query planning are written below.
function subgraphServe(port: number, typeDefs: DocumentNode, resolvers: GraphQLResolverMap) {
const yoga = createYoga({ schema: buildSubgraphSchema([{ typeDefs, resolvers }]), graphqlEndpoint: "/graphql", logging: false });
return new Elysia().all("/graphql", ({ request }) => yoga.fetch(request), { parse: "none" }).listen(port);
}
// Accounts subgraph: owner of Account; @key lets others extend it and the gateway hydrate it from its id.
const ACCOUNTS = [{ id: "CC-0001", holderName: "Ana Beatriz Costa", balanceCents: 842_050 }, { id: "CC-0002", holderName: "Carlos Eduardo Lima", balanceCents: 3_210_000 }];
const accounts = subgraphServe(ACCOUNTS_PORT, parse(`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"])
type Account @key(fields: "id") { id: ID! holderName: String! balanceCents: Int! }
type Query { accounts: [Account!]! }
`), { Query: { accounts: () => ACCOUNTS }, Account: { __resolveReference: ({ id }: { id: string }) => ACCOUNTS.find((account) => account.id === id) } });
// Transactions subgraph: owner of Transaction, contributes Account.transactions by the same key; never calls accounts.
const LEDGER = [{ accountId: "CC-0001", description: "PIX recebido", amountCents: 150_000 }, { accountId: "CC-0001", description: "Boleto energia", amountCents: -18_940 }, { accountId: "CC-0002", description: "TED enviada", amountCents: -200_000 }];
const transactions = subgraphServe(TRANSACTIONS_PORT, parse(`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"])
type Account @key(fields: "id") { id: ID! transactions: [Transaction!]! }
type Transaction { description: String! amountCents: Int! }
`), { Account: { __resolveReference: ({ id }: { id: string }) => ({ id }), transactions: ({ id }: { id: string }) => LEDGER.filter((entry) => entry.accountId === id) } });
type GraphqlReply = { data?: Record<string, unknown>; errors?: { message: string }[] };
type Entity = Record<string, unknown>;
const graphqlPost = async (url: string, query: string, variables?: Record<string, unknown>) => {
const reply = (await (await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query, variables }) })).json()) as GraphqlReply;
if (reply.errors?.length || !reply.data) throw new Error(`subgraph ${url}: ${reply.errors?.map((error) => error.message).join("; ")}`);
return reply.data;
};
const selectionPrint = (fields: FieldNode[]) => fields.map(print).join(" ").replace(/\s+/g, " ");
const typeName = (type: TypeNode): string => (type.kind === Kind.NAMED_TYPE ? type.name.value : typeName(type.type));
// Composition: reads each subgraph's own SDL ({ _service { sdl } }) and maps every field to the one subgraph that resolves it.
// Key fields are shared by definition; any other field claimed by two subgraphs fails here, before a query runs.
const subgraphs = { accounts: `http://localhost:${ACCOUNTS_PORT}/graphql`, transactions: `http://localhost:${TRANSACTIONS_PORT}/graphql` };
const fieldOwners = new Map<string, { subgraph: string; returns: string }>();
const entityKeys = new Map<string, string>();
for (const [subgraph, url] of Object.entries(subgraphs)) {
const sdl = ((await graphqlPost(url, "{ _service { sdl } }"))["_service"] as { sdl: string }).sdl;
for (const definition of parse(sdl).definitions) {
// Underscore types and fields (_Service, _entities) are the federation protocol itself, present in every subgraph.
if ((definition.kind !== Kind.OBJECT_TYPE_DEFINITION && definition.kind !== Kind.OBJECT_TYPE_EXTENSION) || definition.name.value.startsWith("_")) continue;
const keyArgument = definition.directives?.find((directive) => directive.name.value === "key")?.arguments?.[0]?.value;
if (keyArgument?.kind === Kind.STRING) entityKeys.set(definition.name.value, keyArgument.value);
for (const field of (definition.fields ?? []).filter((candidate) => !candidate.name.value.startsWith("_"))) {
const coordinate = `${definition.name.value}.${field.name.value}`;
const owner = fieldOwners.get(coordinate);
if (owner && entityKeys.get(definition.name.value) !== field.name.value) throw new Error(`composition failed: ${coordinate} in ${owner.subgraph} and ${subgraph}`);
if (!owner) fieldOwners.set(coordinate, { subgraph, returns: typeName(field.type) });
}
}
}
console.log(` [COMPOSITION] ${[...fieldOwners].map(([coordinate, owner]) => `${coordinate}→${owner.subgraph}`).join(" ")}`);
// Gateway: the root field goes to its owner with the entity key added; each other subgraph gets one _entities call with every key.
// Known limit: plans one level of entities, enough for this supergraph; a production planner recurses.
async function gatewayExecute(query: string): Promise<{ data: Record<string, unknown> }> {
const operation = parse(query).definitions[0];
if (operation?.kind !== Kind.OPERATION_DEFINITION) throw new Error("only operations are supported");
const data: Record<string, unknown> = {};
for (const root of operation.selectionSet.selections as FieldNode[]) {
const rootOwner = fieldOwners.get(`Query.${root.name.value}`)!;
const entityType = rootOwner.returns;
const key = entityKeys.get(entityType)!;
const fieldsBySubgraph = Map.groupBy((root.selectionSet?.selections ?? []) as FieldNode[], (field) => fieldOwners.get(`${entityType}.${field.name.value}`)!.subgraph);
const ownFields = fieldsBySubgraph.get(rootOwner.subgraph) ?? [];
const rootQuery = `{ ${root.name.value} { ${key} ${selectionPrint(ownFields)} } }`;
console.log(` [GATEWAY] ${rootOwner.subgraph} ← ${rootQuery}`);
const entities = (await graphqlPost(subgraphs[rootOwner.subgraph as keyof typeof subgraphs], rootQuery))[root.name.value] as Entity[];
for (const [subgraph, fields] of fieldsBySubgraph) {
if (subgraph === rootOwner.subgraph) continue;
const representations = entities.map((entity) => ({ __typename: entityType, [key]: entity[key] }));
console.log(` [GATEWAY] ${subgraph} ← _entities(${representations.length} ${entityType}) { ${selectionPrint(fields)} }`);
const reply = await graphqlPost(subgraphs[subgraph as keyof typeof subgraphs], `query ($representations: [_Any!]!) { _entities(representations: $representations) { ... on ${entityType} { ${selectionPrint(fields)} } } }`, { representations });
// _entities answers in the order of the representations: position i completes entity i.
(reply["_entities"] as Entity[]).forEach((part, index) => Object.assign(entities[index]!, part));
}
// The key was added for the join only: the client gets exactly the fields it selected.
if (!ownFields.some((field) => field.name.value === key)) for (const entity of entities) delete entity[key];
data[root.name.value] = entities;
}
return { data };
}
const result = await gatewayExecute("{ accounts { holderName balanceCents transactions { description amountCents } } }");
console.log(` [CLIENT] ${JSON.stringify(result)}`);
await Promise.all([accounts.stop(true), transactions.stop(true)]);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com GraphQL Federation?
Um subgrafo por serviço. Abrir Microsserviços
Seu progresso
0/157 estudados
Fica salvo só neste navegador.