graphql - Apollo gateway com typescript não aceita ID de usuário no contexto
Tenho tentado implementar o novo gateway da Apollo usando TypeScript. Mas continuo enfrentando um único problema de TypeScript que simplesmente não consigo resolver. A mensagem de erro é "Property 'userId' does not exist on type 'TContext'.ts(2339)". Note que estou tentando implementar na AWS Lambda.
Pelo que eu posso ver olhando o código-fonte do pacote, TContext=Record é um objeto, mas não parece resolver.
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']
}
});
Editar Atualizar conforme abaixo parece levar ao mesmo problema.
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);
}
});
}
});
Resposta #1
Primeiro, crie uma interface que irá descrever seu contexto GraphQL
interface MyContext{
userId: string;
}
Então adicione o parâmetro de tipo MyContext ao método willSendRequest assim
...
willSendRequest<MyContext>({request, context}) {
...
Agora o compilador sabe que o contexto é do tipo MyContext.
