resolvers.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const { forwardTo } = require('prisma-binding')
  2. const bcrypt = require('bcryptjs')
  3. const jwt = require('jsonwebtoken')
  4. const LoginError = new Error('You must be logged in.')
  5. const Query = {
  6. users: forwardTo('db'),
  7. trainings: forwardTo('db'),
  8. me: (parent, args, context, info) => {
  9. if (!context.request.userId) throw new Error('Not logged in.')
  10. return context.db.query.user({ where: { id: context.request.userId } }, info)
  11. }
  12. }
  13. const Mutation = {
  14. createUser: async (parent, args, context, info) => {
  15. const email = args.email.toLowerCase()
  16. const password = await bcrypt.hash(args.password, 10)
  17. console.log(email, password)
  18. const user = await context.db.mutation.createUser(
  19. {
  20. data: {
  21. ...args,
  22. email,
  23. password
  24. }
  25. },
  26. info
  27. )
  28. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  29. context.response.cookie('token', token, {
  30. httpOnly: true,
  31. maxAge: 7 * 24 * 3600 * 1000
  32. })
  33. return user
  34. },
  35. signup: async (parent, args, ctx, info) => {
  36. const email = args.email.toLowerCase()
  37. const password = await bcrypt.hash(args.password, 10)
  38. const user = await ctx.db.mutation.createUser(
  39. {
  40. data: {
  41. ...args,
  42. email,
  43. password
  44. }
  45. },
  46. info
  47. )
  48. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  49. ctx.response.cookie('token', token, {
  50. httpOnly: true,
  51. maxAge: 24 * 60 * 60 * 1000
  52. })
  53. return user
  54. },
  55. login: async (parent, args, context, info) => {
  56. const { email, password } = args
  57. const user = await context.db.query.user({ where: { email } })
  58. if (!user) throw new Error('User not found')
  59. const valid = await bcrypt.compare(password, user.password)
  60. if (!valid) throw new Error('Invalid password')
  61. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  62. context.response.cookie(
  63. 'token',
  64. token,
  65. {
  66. httpOnly: true,
  67. maxAge: 7 * 24 * 3600 * 1000
  68. },
  69. info
  70. )
  71. return user
  72. },
  73. logout: async (parent, args, context, info) => {
  74. context.response.clearCookie('token')
  75. return 'Logged out.'
  76. },
  77. createTraining: async (parent, args, context, info) => {
  78. const { userId } = context.request
  79. // if (!userId) throw LoginError
  80. const training = await context.db.mutation.createTraining(
  81. {
  82. data: args
  83. },
  84. info
  85. )
  86. return training
  87. }
  88. }
  89. const resolvers = {
  90. Query,
  91. Mutation
  92. }
  93. module.exports = { resolvers }