如何通过ApolloGateway为不同子图设置不同请求头?
为Apollo Gateway不同子图配置独立请求头
一、子图Introspection(组合Supergraph时)的独立请求头
你当前用全局introspectionHeaders给所有子图配置了统一的 introspect 请求头,要实现子图差异化配置,直接在每个子图的配置对象里单独定义introspectionHeaders即可,它会覆盖全局的配置项:
const gateway = new ApolloGateway({ supergraphSdl: new IntrospectAndCompose({ subgraphs: [ { name: 'products', url: 'https://products-service.dev/graphql', // 为products子图单独配置introspect请求头 introspectionHeaders: { Authorization: 'Bearer products-token-123' } }, { name: 'reviews', url: 'https://reviews-service.dev/graphql', // 为reviews子图单独配置introspect请求头 introspectionHeaders: { Authorization: 'Bearer reviews-token-456', 'X-Custom-Header': 'review-service-only' } }, ], // 可选:全局默认头,未单独配置的子图会使用这个 introspectionHeaders: { 'X-Global-Header': 'common-for-all' }, }), });
这样Apollo Gateway在组合Supergraph、向各个子图发起introspect请求时,会自动使用对应子图配置的专属请求头。
二、运行时转发请求到子图的独立请求头
如果需要在网关处理客户端请求时,给不同子图转发不同的运行时请求头,要用到buildService方法自定义数据源:
const gateway = new ApolloGateway({ supergraphSdl: new IntrospectAndCompose({ subgraphs: [ { name: 'products', url: 'https://products-service.dev/graphql' }, { name: 'reviews', url: 'https://reviews-service.dev/graphql' }, ], introspectionHeaders: { Authorization: 'Bearer abc123', }, }), // 为每个子图构建自定义数据源,添加专属请求头 buildService({ name, url }) { const service = new RemoteGraphQLDataSource({ url }); service.willSendRequest = async ({ request, context }) => { // 根据子图名称设置不同的请求头 switch(name) { case 'products': request.http.headers.set('Authorization', 'Bearer products-runtime-token'); request.http.headers.set('X-Product-Env', 'production'); break; case 'reviews': request.http.headers.set('Authorization', 'Bearer reviews-runtime-token'); request.http.headers.set('X-Review-Region', 'us-west'); break; default: // 未匹配到的子图使用默认头 request.http.headers.set('X-Global-Runtime-Header', 'common'); } }; return service; }, });
通过willSendRequest钩子,在网关将请求转发到子图之前,根据子图名称动态添加专属请求头,满足运行时的差异化需求。
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

