如何调试ApolloServer的上下文函数?

时间:2019-08-29 13:42:25

标签: javascript node.js apollo apollo-server javascript-debugger

我正在尝试遵循GraphQL教程(https://www.apollographql.com/docs/tutorial/resolvers/),但是在尝试预订行程时,却在操场上遇到了一个错误,堆栈跟踪如下所示:

 "TypeError: Cannot read property 'id' of null",
            "    at UserAPI.bookTrips (/Users/kurtpeek/Documents/Scratch/fullstack-tutorial/start/server/src/datasources/user.js:35:38)",

enter image description here

src/index.js中,ApolloServerhttps://www.apollographql.com/docs/apollo-server/api/apollo-server/)是用异步context()函数定义的,如下所示:

const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const { createStore } = require('./utils');
const resolvers = require('./resolvers');

const LaunchAPI = require('./datasources/launch');
const UserAPI = require('./datasources/user');
const isEmail = require('isemail');

const store = createStore();

const server = new ApolloServer({
  context: async ({ req }) => {
    debugger;
    const auth = (req.headers && req.headers.authorization) || '';
    const email = Buffer.from(auth, 'base64').toString('ascii');
    if (!isEmail.validate(email)) return { user: null };

    const users = await store.users.findOrCreate({ where: { email }});
    const user = users && users[0] ? users[0] : null;

    return { user: { ...user.dataValues }};
  },
  typeDefs,
  resolvers,
  dataSources: () => ({
    launchAPI: new LaunchAPI(),
    userAPI: new UserAPI({ store })
  })
});

server.listen().then(({ url }) => {
  console.log(`? Server ready at ${url}`);
});

由于我看到的错误是上下文usernull的结果,所以我想逐步通过context()方法检查标头并查看其是否包含有效的(编码的)电子邮件;如您所见,我在该函数的开始处设置了一个debugger断点。

但是,当我运行node inspect src/index.js时,我立即进入IntrospectionQuery的调试器:

enter image description here

如果我按下“继续执行脚本”按钮,我将立即回到相同的断点。

这与context()async函数的事实有关吗?如何使用调试器逐步完成context()方法?

1 个答案:

答案 0 :(得分:1)

最后,我只是使用console.log()命令对其进行了调试。我不小心将authorization放在了“查询变量”部分而不是“ HTTP头”部分。将其移至“ HTTP标头”会产生所需的结果:

enter image description here