【问题标题】:Apollo Server: How to access 'context' outside of resolvers in Dataloader from REST API DatasourceApollo Server:如何从 REST API 数据源访问 Dataloader 中解析器之外的“上下文”
【发布时间】:2021-01-17 07:39:17
【问题描述】:

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

问题陈述:

为了在我的DataLoader 中进行身份验证,我想访问“上下文”。此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;

【问题讨论】:

    标签: javascript graphql apollo apollo-server dataloader


    【解决方案1】:

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

    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 Docs 本身中的 here 所述。因此,如果您想保留源代码,可以一起摆脱加载器。

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

    【讨论】:

    • 这行得通 - 非常感谢!我现在将我的数据加载器重新排列在一个单独的文件夹中,并将它们导入我的 index.js
    猜你喜欢
    • 2020-10-16
    • 2020-09-12
    • 2018-02-18
    • 2016-12-10
    • 2020-11-11
    • 2021-04-06
    • 2020-11-19
    • 2023-02-03
    • 2020-04-01
    相关资源
    最近更新 更多