我正在服务器中设置授权,代码应将令牌传递到Middleware
,但是context.user
应该返回令牌的值,但应该返回null。
如何解决?
const apollo = new ApolloServer({
typeDefs: schema,
resolvers,
playground: true,
introspection: true,
context: async ({ req, connection }) => {
if (connection) {
return connection.context;
} else {
const token = req.headers.authorization || '';
const language = req.headers.language || 'ar';
const user = token ? await _getUser(token.replace("Bearer ","")) : null;
return { user, language };
}
},
});
async function _getUser(token) {
return new Promise((resolve, reject) => {
User.findOne({token: token}, (err, user) => {
resolve(user);
}).populate('role').exec();
})
}