简体   繁体   English

使用 graphql 和 apollo-server 在解析器中获取会话

[英]Getting session in resolvers using graphql and apollo-server

I'm new to graphql, i was trying to make an authentication system with session files.我是graphql的新手,我试图用会话文件制作一个身份验证系统。 Here's my code :这是我的代码:

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}`)
)

The problem here is that i can't get the session in the testFunc Resolver.这里的问题是我无法在 testFunc Resolver 中获取会话。

The console.log(context) shows this: console.log(context) 显示了这一点:

{ _extensionStack:
   GraphQLExtensionStack {
     extensions:
      [ [EngineFederatedTracingExtension], [CacheControlExtension] ] } }

The console.log(session) shows "undefined" console.log(session) 显示“未定义”

And in the graphql interface, when i call testFunc i have "Cannot set property 'something' of undefined" obviously.在 graphql 界面中,当我调用 testFunc 时,我显然“无法设置未定义的属性‘某物’”。

I didn't migrate from apollo-server v1 to v2 since i've directly started from v2.我没有从 apollo-server v1 迁移到 v2,因为我是直接从 v2 开始的。 I tried setting "request.credentials" to "input" in the graphql settings as said in this post: Apollo 2.0.0 Graphql cookie session but it didn't change anything either.我尝试在graphql设置中将“request.credentials”设置为“input”,如这篇文章所述: Apollo 2.0.0 Graphql cookie session,但它也没有改变任何东西。

Ok, i figured it out, i just had to replace this:好的,我想通了,我只需要替换这个:

const server = new ApolloServer({
  schema: buildFederatedSchema([{
    typeDefs,
    resolvers,
    context: ({ req }) => ({ session: req.session })
  }])
})

by this:这样:

const server = new ApolloServer({
  schema: buildFederatedSchema([{
    typeDefs,
    resolvers
  }]),
  context: ({ req }) => ({ session: req.session })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM