graphql - Apollo gateway với typescript sẽ không chấp nhận ID người dùng trong context
Tôi đã cố gắng triển khai cổng thông tin mới của Apollo bằng typescript. Nhưng tôi liên tục gặp một vấn đề với typescript mà tôi không thể giải quyết được. Thông báo lỗi là "Property 'userId' does not exist on type 'TContext'.ts(2339)". Lưu ý tôi đang cố gắng triển khai trên AWS Lambda.
Theo như tôi có thể thấy bằng cách nhìn vào mã nguồn gói, TContext=Record là một đối tượng nhưng dường như nó không được giải quyết.
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']
}
});
Chỉnh sửa Cập nhật theo những điều dưới đây có vẻ dẫn đến cùng một vấn đề.
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);
}
});
}
});
Câu trả lời #1
Đầu tiên, tạo một giao diện, sẽ mô tả ngữ cảnh graphql của bạn
interface MyContext{
userId: string;
}
Sau đó thêm tham số kiểu MyContext vào phương thức willSendRequest như sau
...
willSendRequest<MyContext>({request, context}) {
...
Bây giờ trình biên dịch biết rằng ngữ cảnh là loại MyContext.
