Шлюз Apollo с машинописным текстом не принимает идентификатор пользователя в контексте
Я пытался реализовать новый шлюз Apollo, используя машинописный текст. Но я все время сталкиваюсь с одной проблемой машинописного текста, которую, кажется, просто не могу решить. Сообщение об ошибке: "Свойство 'userId' не существует для типа 'TContext'.ts(2339)". Обратите внимание, что я пытаюсь реализовать на 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);
}
});
}
});
1 ответ
Сначала создайте интерфейс, который будет описывать ваш контекст graphql
interface MyContext{
userId: string;
}
Затем добавьте параметр типа MyContext в метод willSendRequest следующим образом
...
willSendRequest<MyContext>({request, context}) {
...
Теперь компилятор знает, что этот контекст имеет тип MyContext.