将express-graphql迁移到阿波罗服务器v2

时间:2018-06-24 12:06:37

标签: graphql apollo-server

我正在尝试将express-graphql切换到apollo-server v2,但是我在迁移软件包方面遇到了困难,尤其是在使用passportjs和会话的情况下。

我当前使用express-graphql进行的设置:

const schema = include('schema')

const app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use(session({
  secret: process.env.SESSION_SECRET,
  name: 'sessionId',
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection }),
}))

app.use(passport.initialize())
app.use(passport.session())

app.use('/graphql', expressGraphQL({ schema }))

const server = http.createServer(app)

server.listen(8000, '0.0.0.0', () =>
  console.log('Server running on port 8000')
)

现在使用apollo-server-express @ rc:

const schema = include('schema')

const app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use(session({
  secret: process.env.SESSION_SECRET,
  name: 'sessionId',
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection }),
}))

app.use(passport.initialize())
app.use(passport.session())

const apollo = new ApolloServer({
  schema,
  context: ({ req: { user, session } }) => ({ user, session })
})
apollo.applyMiddleware({ app, path: '/graphql' })

server.listen(8000, '0.0.0.0', () =>
  console.log('Server running on port 8000')
)

有了这个,我得到了上下文中的usersession对象,并且像以前一样工作,但是当我尝试通过{{1}来login()logout()个用户时}它显示context

好的,login is not a function,然后再试一次,但是现在我得到了context: ({ req: { user, session, login, logout } }) => ({ user, session, login, logout })

在我不必使用express-graphql设置上下文之前,这就是我要坚持的地方。请帮忙吗?

0 个答案:

没有答案