resolvers.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const { forwardTo } = require('prisma-binding')
  2. const bcrypt = require('bcryptjs')
  3. const jwt = require('jsonwebtoken')
  4. const Query = {
  5. users: forwardTo('db'),
  6. me: (parent, args, context, info) => {
  7. if (!context.request.userId) throw new Error('Not logged in.')
  8. return context.db.query.user(
  9. { where: { id: context.request.userId } },
  10. info
  11. )
  12. }
  13. }
  14. const Mutation = {
  15. createUser: async (parent, args, context, info) => {
  16. const email = args.email.toLowerCase()
  17. const password = await bcrypt.hash(args.password, 10)
  18. console.log(email, password)
  19. const user = await context.db.mutation.createUser(
  20. {
  21. data: {
  22. ...args,
  23. email,
  24. password
  25. }
  26. },
  27. info
  28. )
  29. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  30. context.response.cookie('token', token, {
  31. httpOnly: true,
  32. maxAge: 7 * 24 * 3600 * 1000
  33. })
  34. return user
  35. },
  36. userLogin: async (parent, args, context, info) => {
  37. const { email, password } = args
  38. const user = await context.db.query.user({ where: { email } })
  39. if (!user) throw new Error('User not found')
  40. const valid = await bcrypt.compare(password, user.password)
  41. if (!valid) throw new Error('Invalid password')
  42. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  43. context.response.cookie(
  44. 'token',
  45. token,
  46. {
  47. httpOnly: true,
  48. maxAge: 7 * 24 * 3600 * 1000
  49. },
  50. info
  51. )
  52. return user
  53. },
  54. userLogout: async (parent, args, context, info) => {
  55. context.response.clearCookie('token')
  56. return 'Logged out.'
  57. }
  58. }
  59. const resolvers = {
  60. Query,
  61. Mutation
  62. }
  63. module.exports = { resolvers }