我正在使用Apollo Server 2 (但这个问题不仅限于Apollo)和原始的Express.js(使用apollo-server-express
)。
除了Express会话(session)机制之外,一切都很好,包括订阅(Subscription)。
问题:
我正在使用cookie-session(https://github.com/expressjs/cookie-session,但我认为express-session中间件也是如此),当我的浏览器与服务器建立新连接时,ApolloServer的onConnect
钩子没有req
属性,也没有req.session
等等...
我能做的是在onConnect
生命周期钩子中从webSocket.upgradeReq.headers.cookie
解析cookie,但我觉得这非常诡异。
代码:
const { ApolloServer } = require('apollo-server-express')
const typeDefs = require('../src/graphql/types')
const resolvers = require('../src/graphql/resolvers')
const models = require('../src/models')
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, connection }) => {
// connection exists only on webSocket connection
if (connection) {
return {
currentUser: connection.context.currentUser // <-- I NEED THIS!
}
}
// if not a (webSocket) connection it is a "default" HTTP call
return {
models,
currentUser: { id: req.user.id }
}
},
subscriptions: {
onConnect: (connectionParams, webSocket) => {
// "connectionParams" is from the client but I cannot use it because cookies are HTTP-Only
// I can retrieve cookies from here: "webSocket.upgradeReq.headers.cookie" but then I need to parse them which seems a bit hacky to me
// return { currentUser: req.user.id } // <-- I NEED THIS (req.user.id doesn't exists)!
}
}
})
module.exports = apolloServer
我在Apollo Server文档网站上找不到任何内容(其他主题都有很好的文档!)。
我做错了什么?