0
votes

I'm learning GraphQL via https://github.com/the-road-to-graphql/fullstack-apollo-express-postgresql-boilerplate

and I'm wondering how to set cookies from a resolver as I'm used to using Express to do so.

signIn: async (
  parent,
  { login, password },
  { models, secret },
) => {
  const user = await models.User.findByLogin(login);

  if (!user) {
    throw new UserInputError(
      'No user found with this login credentials.',
    );
  }

  const isValid = await user.validatePassword(password);

  if (!isValid) {
    throw new AuthenticationError('Invalid password.');
  }

  return { token: createToken(user, secret, '5m') };
},

instead of returning a token obj, how can I access the response object and add a cookie?

1

1 Answers

1
votes

You can achieve this using the context object, looking at the example you send. You will need to return the res variable from this function https://github.com/the-road-to-graphql/fullstack-apollo-express-postgresql-boilerplate/blob/master/src/index.js#L55

The context object is located at the 3rd argument to your resolver. The context is created on each request & available to all resolvers.

Example:

const server = new ApolloServer({
  context: ({res}) => ({res})
});

function resolver(root, args, context){
  context.res// express
}