我正在尝试遵循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)",
在src/index.js
中,ApolloServer
(https://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}`);
});
由于我看到的错误是上下文user
为null
的结果,所以我想逐步通过context()
方法检查标头并查看其是否包含有效的(编码的)电子邮件;如您所见,我在该函数的开始处设置了一个debugger
断点。
但是,当我运行node inspect src/index.js
时,我立即进入IntrospectionQuery
的调试器:
如果我按下“继续执行脚本”按钮,我将立即回到相同的断点。
这与context()
是async
函数的事实有关吗?如何使用调试器逐步完成context()
方法?