我一直在尝试使用 typescript 实现 Apollo 的新网关。但是我一直遇到一个我似乎无法解决的打字稿问题。错误消息是“类型 'TContext'.ts(2339) 上不存在属性 'userId'”。注意我正在尝试在 AWS Lambda 上实施。
据我所知,通过查看包源代码 TContext = Record 是一个对象,但它似乎没有解决。
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);
}
});
}
});