- 安装相应的库
npm install @apollo/federation graphql
- 在每个子服务的 schema 中添加
@key
指令
type Product @key(fields: "id") {
id: ID!
name: String!
price: Float!
}
type Query {
product(id: ID!): Product
}
- 在网关服务中使用
federatedSchema
方法创建 schema
const { ApolloServer } = require('apollo-server');
const { ApolloGateway, RemoteGraphQLDataSource } = require('@apollo/gateway');
const { federatedSchema } = require('@apollo/federation');
const gateway = new ApolloGateway({
serviceList: [
{ name: "products", url: "http://localhost:4001" },
{ name: "users", url: "http://localhost:4002" }
],
buildService({ url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
request.http.headers.set('user-id', context.userId || '');
}
});
}
});
const server = new ApolloServer({
schema: federatedSchema({ gateway }),
context: ({ req }) => {
const userId = req.headers.authorization || '';
return { userId };
}
});
server.listen().then(({ url }) => {
console.log(`� Server ready at ${url}`);
});
- 运行服务
node services/products.js
node services/users.js
node gateway.js
- 对 schema 进行验证
npx graphql-cli validate --rules @apollo/federation/no-circular-references schema.graphql