graphql - Apollo gateway s typescriptom neće prihvatiti korisnički ID u kontekstu
Pokušavam implementirati novi Apollo gateway koristeći TypeScript. Ali stalno naiđem na jedan problem s TypeScriptom koji jednostavno ne mogu riješiti. Poruka o pogrešci je "Property 'userId' does not exist on type 'TContext'.ts(2339)". Napomena: pokušavam implementirati na AWS Lambda.
Koliko ja mogu vidjeti gledajući izvorni kod paketa, TContext=Record je objekt, ali se čini da se ne rješava.
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']
}
});
Uredi Ažuriranje prema dolje čini se da dovodi do istog 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);
}
});
}
});
Odgovor #1
Prvo, stvorite sučelje koje će opisivati vaš graphql kontekst
interface MyContext{
userId: string;
}
Zatim dodajte parametar tipa MyContext u metodu willSendRequest ovako
...
willSendRequest<MyContext>({request, context}) {
...
Sada kompajler zna da je kontekst tipa MyContext.
