Reputation: 2153
I have a graphql server based on apollo-server-express.
My resolvers typically do REST requests on a legacy API. One of the resolvers performs user authentication by sending the username and password to the backend server. The response includes a token that is used for the authentication of subsequent requests.
At the moment I pass the token to my client application includes it in the subsequent requests.
I would now like to save this token in the epxress-session so that it can be then be passed in the context of subsequent resolvers implicitly,
but I don't see how I can update request.session after a response is received in the resolver.
Upvotes: 2
Views: 2567
Reputation: 84687
First, expose the session object to the resolvers by including it in your context. express-graphql
includes the request object as your context by default, but I don't think Apollo server's middleware shares that behavior -- instead we need to explicitly define the context.
app.use('/graphql', bodyParser.json(), (req, res, next) => {
const context = { session:req.session }
graphqlExpress({ schema })(req, res, next)
})
Then, inside your resolver, just add the returned token to the session object:
const loginResolver = (obj, {username, password}, context) => {
return apiAuthCall(username, password)
.then(token => {
context.session.token = token
return // whatever other data, could just be a boolean indicated whether the login was successful
})
}
Upvotes: 3