1
votes

I'm new to graphql, i was trying to make an authentication system with session files. 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.

The console.log(context) shows this:

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

The console.log(session) shows "undefined"

And in the graphql interface, when i call testFunc i have "Cannot set property 'something' of undefined" obviously.

I didn't migrate from apollo-server v1 to v2 since i've directly started from 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.

1

1 Answers

1
votes

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