Apollo RESTDataSource 中未定义上下文

问题描述 投票:0回答:1

从 Apollo v2 升级到 v3 时,我尝试对身份验证服务器进行一些外部 API 调用。目前,我正在使用 nock 来拦截单元测试中的请求。

当我尝试在请求标头中附加令牌时,GET 请求始终失败,因为上下文未定义。为什么这里的上下文是未定义的?这在升级之前有效。

服务器.js

const {ApolloServer} = require('apollo-server-koa'),
CustomApi = require('../service/customapi'),
...;

const apolloServer = new ApolloServer({
    typeDefs: [DateTypeDefinition, root.typeDef, user.typeDef, ...],
    resolvers: [{Date: DateResolver}, root.resolvers, user.resolvers, ...],
    validationRules: [depthLimit(10)],
    plugins: [
        graphqlLogger
    ],
    dataSources: () => {
        return {
            customApi: new CustomApi()
        };
    },
    context: async (req) => {
        const user = await extract(req);
        return {
            user,
            ...
        }
    }
})

module.exports = apolloServer;

resolvers.js

syncAccount: async (parent, _, context) => {
        allowed(context.user);
        const reviewer = await getReviewerByEmail(context.user.email);
        if (reviewer && reviewer.status === 'INVITED') {
            const account = await context.dataSources.customApi.getAccount();
            ...
}

自定义API.js

const {RESTDataSource} = require('@apollo/datasource-rest'),
config = require('config')

class CustomAPI extends RESTDataSource {
        constructor() {
            super();
            this.baseURL = `${config.customapi.url}/path/api`;
        }

        willSendRequest(path, request) {
            //ERROR HERE
            console.log("willSendRequest - this.context: ", this.context); // prints undefined
            request.headers.set('Authorization', this.context.user.token);
        }

        async getAccount() {
            return await this.get('account');
        }
        ...
}

package.json 版本:

"@apollo/datasource-rest": "^6.2.2",
"@koa/cors": "^3.1.0",
"apollo-server": "^3.13.0",
"apollo-server-koa": "^3.13.0",
"dataloader": "^2.0.0",
"graphql": "^16.8.1",
"graphql-depth-limit": "^1.1.0",
"graphql-scalars": "^1.22.4",
"graphql-upload": "^13.0.0",
"koa": "^2.13.0",
"koa-bodyparser": "^4.3.0",
"koa-jwt": "^4.0.0",
"koa-router": "^9.4.0",
...
node.js apollo nock restdatasource
1个回答
0
投票

我没有从 RESTDataSource 中检索上下文,而是传入了它,这就达到了目的:

async getAccount(token) {
        return await this.get('account', undefined, {
            headers: {
                'Authorization': token
            }
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.