我是graphql的新手,我试图使用会话文件创建身份验证系统。 这是我的代码:
const { ApolloServer, gql } = require('apollo-server-express')
const { buildFederatedSchema } = require("@apollo/federation")
const app = require('express')()
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const typeDefs = gql`
type Query {
testFunc: String
}
`
const resolvers = {
Query: {
testFunc: (_, args, context) => {
console.log(context)
const { session } = context
console.log(session)
session.something = "hello"
return session.something
}
}
}
app.use(session({
store: new FileStore({}),
secret: 'secret'
}))
const server = new ApolloServer({
schema: buildFederatedSchema([{
typeDefs,
resolvers,
context: ({ req }) => ({ session: req.session })
}])
})
server.applyMiddleware({app})
app.listen({ port: 4014 }, () =>
console.log(`? Server ready at http://localhost:4014${server.graphqlPath}`)
)
这里的问题是我无法在testFunc Resolver中获得会话。
console.log(上下文)显示此内容:
{ _extensionStack:
GraphQLExtensionStack {
extensions:
[ [EngineFederatedTracingExtension], [CacheControlExtension] ] } }
console.log(session)显示“未定义”
在graphql界面中,当我调用testFunc时,我显然拥有“无法设置未定义的属性””。
由于我直接从v2开始,所以我没有从apollo服务器v1迁移到v2。 我尝试按照以下博文中所述在graphql设置中将“ request.credentials”设置为“ input”:Apollo 2.0.0 Graphql cookie session,但也没有任何改变。
答案 0 :(得分:0)
好吧,我想通了,我只需要替换一下:
const server = new ApolloServer({
schema: buildFederatedSchema([{
typeDefs,
resolvers,
context: ({ req }) => ({ session: req.session })
}])
})
由此:
const server = new ApolloServer({
schema: buildFederatedSchema([{
typeDefs,
resolvers
}]),
context: ({ req }) => ({ session: req.session })
})