带打字稿的Apollo网关在上下文中不接受用户ID

时间:2019-09-13 10:52:53

标签: typescript graphql apollo-server apollo-gateway

我一直在尝试使用Typescript实现Apollo的新网关。但是我一直遇到一个我似乎无法解决的打字稿问题。错误消息是“类型'TContext'.ts(2339)上不存在属性'userId'”。注意我正在尝试在AWS Lambda上实施。

到目前为止,通过查看包源代码TContext =记录,您可以看到=记录是一个对象,但它似乎无法解决。

#define N 4

// Data structure to store graph
struct Graph {
    // An array of pointers to Node to represent adjacency list
    struct Node* head[N];
};

修改 根据以下内容进行更新似乎会导致相同的问题。

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']
  }
});

1 个答案:

答案 0 :(得分:1)

首先,创建一个接口,该接口将描述您的graphql上下文

i == 3263

然后将MyContext类型参数添加到willSendRequest方法中

interface MyContext{
    userId: string;
}

现在,编译器知道上下文是MyContext类型。