Apollo 服务器:如何从 REST API 数据源访问 'context' Dataloader 中的解析器外部

Apollo Server: How to access 'context' outside of resolvers in Dataloader from REST API Datasource

希望有人能帮我解决这个小问题,我现在还想不通。

问题陈述:

为了在我的 DataLoader 中进行身份验证,我想访问 'context'。此 DataLoader 在单独的路径 /loaders 中定义。在我的 resolvers.js 文件中,我可以使用 dataSources.userAPI.getAllUsers() 很好地访问我的上下文。 但是如何在我的服务器端应用程序中的其他任何地方访问它,比如 f.e。在我的 /loaders 文件夹中? 我只是不知道如何访问我的上下文对象,然后将令牌传递给 DataLoader,然后从我的 API 加载数据,然后将此数据传递给我的 resolvers.js 文件. 非常感谢您的帮助,我不知道如何解决这个简单的事情..谢谢!

代码来了:

index.js

const express = require('express');
const connectDB = require('./config/db');
const path = require('path');
var app = express();
const cors = require('cors')
const axios = require('axios')

// apollo graphql
const { ApolloServer } = require('apollo-server-express');
const DataLoader = require('dataloader')
const { userDataLoader } = require('./loaders/index')

// Connect Database
connectDB();

// gql import
const typeDefs = require('./schema');
const resolvers = require('./resolvers')

// apis
const UserAPI = require('./datasources/user')


// datasources
const dataSources = () => ({
    userAPI: new UserAPI(),
});

// context
const context = ({ req, res }) => ({

    token: req.headers.authorization || null,
    loaders: {
        userLoader: userDataLoader,
    },
    res
})


// init server
const server = new ApolloServer({
    typeDefs,
    resolvers,
    dataSources,
    context
});

// middleware
app.use(express.json());


// cors
var corsOptions = {
    credentials: true
}
app.use(cors(corsOptions))


// serve middleware
server.applyMiddleware({
    app
});


// run server
app.listen({ port: 4000 }, () =>
    console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);

module.exports = {
    dataSources,
    context,
    typeDefs,
    resolvers,
   loaders,
    ApolloServer,
    UserAPI,
    server,
};

loaders/index.js

   const userDataLoader = require('./user')

module.exports = {
    userDataLoader
}

loaders/user.js

const UserAPI = require('../datasources/users')
// init loader
const userDataLoader = new DataLoader(keys => batchUser(keys))

// batch
const batchUsers = async (keys) => {

   // this part is not working!
   // How to access the UserAPI methods in my DataLoader?
   // Or lets say: How to access context from here,
   // so I can add auth for the server I am requesting data from?

    const userAPI = new UserAPI()
    const users = userAPI.getAllUsers()
        .then(res => {
            return res.data
        })


    return keys.map(userId => users.find(user=> user._id === userId))
}

module.exports = userDataLoader

resolvers.js

// here is just my api call to get the data from my
// dataloader with userLoader.load() and this works perfectly
// if I just make API calls with axios in my loaders/user
// here just a little snippet from the resolver file

....
users: async (parent, args, { loaders }) => {
            const { userLoader } = loaders
            if (!parent.users) {
                return null;
            }
            return await userLoader.load(parent.user)
        },
....

datasources/user.js

const { RESTDataSource } = require('apollo-datasource-rest');

class UserAPI extends RESTDataSource {
    constructor() {
        super()
        this.baseURL = 'http://mybaseurl.com/api'
    }


    willSendRequest(request) {
        request.headers.set('Authorization',
            this.context.token
        );
    }

    async getUserById(id) {
        return this.get(`/users/${id}`)
    }

    async getAllUsers() {
        const data = await this.get('/users');
        return data;
    }
}

module.exports = UserAPI;

我建议创建一个函数来创建数据加载器并在闭包内提供所需的状态,并且根本不使用数据源:

module.exports.createDataloaders = function createDataLoaders(options) {
  const batchUsers = ids => {
    const users = await fetch('/users/', { headers: { Authorization: options.auth } });
    // ...
  }

  return {
    userLoader: new Dataloader(batchUsers);
  };
}

// now in index.js
// context
const context = ({ req, res }) => ({
    token: req.headers.authorization || null,
    loaders: createDataloaders({ auth: req.headers.authorization || null }),
    res
})


// init server
const server = new ApolloServer({
    typeDefs,
    resolvers,
    context
});

或者考虑翻转图层:

const { RESTDataSource } = require('apollo-datasource-rest');

class UserAPI extends RESTDataSource {
    constructor() {
        super()
        this.baseURL = 'http://mybaseurl.com/api'
        this.dataloader = new Dataloader(ids => {
          // use this.get here
        });
    }


    willSendRequest(request) {
        request.headers.set('Authorization',
            this.context.token
        );
    }

    async getUserById(id) {
        return this.dataloader.load(id);
    }

    async getAllUsers() {
        const data = await this.get('/users');
        return data;
    }
}

module.exports = UserAPI;

但数据源并非设计为与 Dataloader 一起使用,如 Apollo 文档本身中所述here。因此,如果你想保留源代码,可以将加载程序全部删除。

基本上他们所说的是包装 rest API 的 GraphQL API 从(全局)请求缓存中受益比从预请求数据加载器中受益更多。跨请求缓存可能会导致授权问题,所以要小心。