const { forwardTo } = require('prisma-binding') const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const Query = { users: forwardTo('db'), me: (parent, args, context, info) => { if (!context.request.userId) throw new Error('Not logged in.') return context.db.query.user( { where: { id: context.request.userId } }, info ) } } const Mutation = { createUser: async (parent, args, context, info) => { const email = args.email.toLowerCase() const password = await bcrypt.hash(args.password, 10) console.log(email, password) const user = await context.db.mutation.createUser( { data: { ...args, email, password } }, info ) const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET) context.response.cookie('token', token, { httpOnly: true, maxAge: 7 * 24 * 3600 * 1000 }) return user }, userLogin: async (parent, args, context, info) => { const { email, password } = args const user = await context.db.query.user({ where: { email } }) if (!user) throw new Error('User not found') const valid = await bcrypt.compare(password, user.password) if (!valid) throw new Error('Invalid password') const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET) context.response.cookie( 'token', token, { httpOnly: true, maxAge: 7 * 24 * 3600 * 1000 }, info ) return user }, userLogout: async (parent, args, context, info) => { context.response.clearCookie('token') return 'Logged out.' } } const resolvers = { Query, Mutation } module.exports = { resolvers }