带有typescript的Apollo网关不接受上下文中的用户ID
我一直在尝试使用typescript实现Apollo的新网关。但我一直遇到一个打字稿的问题,我似乎无法解决。错误消息为“类型“TContext”.ts(2339)”上不存在属性“userId”。注意,我试图在AWS Lambda上实现 据我所知,通过查看包源代码TContext=Record可以看出,它是一个对象,但似乎无法解析带有typescript的Apollo网关不接受上下文中的用户ID,typescript,graphql,apollo-server,apollo-gateway,Typescript,Graphql,Apollo Server,Apollo Gateway,我一直在尝试使用typescript实现Apollo的新网关。但我一直遇到一个打字稿的问题,我似乎无法解决。错误消息为“类型“TContext”.ts(2339)”上不存在属性“userId”。注意,我试图在AWS Lambda上实现 据我所知,通过查看包源代码TContext=Record可以看出,它是一个对象,但似乎无法解析 import { ApolloServer } from 'apollo-server-lambda'; import { ApolloGateway, RemoteG
import { ApolloServer } from 'apollo-server-lambda';
import { ApolloGateway, RemoteGraphQLDataSource } from '@apollo/gateway';
const gateway = new ApolloGateway({
serviceList: [
{ name: 'users', url: 'xx' },
{ name: 'precedents', url: 'xx' }
// other services
],
buildService({ url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
// pass the user's id from the context to underlying services
// as a header called `user-id`
request && request.http && request.http.headers.set('user-id', context.userId);
}
});
}
});
const server = new ApolloServer({
gateway,
subscriptions: false,
context: ({ event, context }) => {
// get the user token from the headers
const token = event.headers.authorization || '';
// try to retrieve a user with the token
const userId = token;
// add the user to the context
return {
headers: event.headers,
functionName: context.functionName,
event,
context,
userId
};
}
});
exports.handler = server.createHandler({
cors: {
origin: true,
credentials: true,
methods: ['POST', 'GET'],
allowedHeaders: ['Content-Type', 'Origin', 'Accept', 'authorization']
}
});
编辑
根据下面的更新似乎会导致相同的问题
interface MyContext{
userId: string;
}
const gateway = new ApolloGateway({
serviceList: [
{ name: 'users', url: 'xx' },
{ name: 'precedents', url: 'xx' }
// other services
],
buildService({ url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest<MyContext>({ request, context } : {request: GraphQLRequest, context: MyContext}) {
// pass the user's id from the context to underlying services
// as a header called `user-id`
request && request.http && request.http.headers.set('user-id', context.userID);
}
});
}
});
接口MyContext{
userId:string;
}
const gateway=新网关({
服务列表:[
{name:'users',url:'xx'},
{name:'先例',url:'xx'}
//其他服务
],
构建服务({url}){
返回新的RemoteGraphQLDataSource({
网址,
willSendRequest({request,context}:{request:GraphQLRequest,context:MyContext}){
//将用户id从上下文传递到基础服务
//作为名为`用户id'的标头`
request&&request.http&&request.http.headers.set('user-id',context.userID);
}
});
}
});
首先,创建一个描述graphql上下文的接口
interface MyContext{
userId: string;
}
然后向willSendRequest方法添加MyContext类型参数,如下所示
...
willSendRequest<MyContext>({request, context}) {
...
。。。
willSendRequest({request,context}){
...
现在编译器知道了,该上下文是MyContext类型。感谢您的回复。很抱歉,我对Typescript还是相当陌生,仍然无法解决Typescript错误。更新后的代码仍然会给出相同的错误?我已经用新代码更新了上面的内容。