-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolvers.js
96 lines (86 loc) · 2.97 KB
/
resolvers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const createToken = (user, secret, expiresIn) => {
return jwt.sign({ email: user.email }, secret, { expiresIn })
}
module.exports = {
Query: {
User: async (_, args, { User, currentUser }) => {
if (!currentUser) {
return null
}
const user = await User.findOne({ email: currentUser.email })
return user
},
Customers: async (_, args, { Customer }) => {
const customers = await Customer.find()
return customers
}
},
Mutation: {
addCustomer: async (_, { name, surname, email, phone, bookDescription, bookPrice, purchaseDate, isbn }, { Customer }) => {
const newCustomer = await new Customer({
name,
surname,
email,
phone,
bookDescription,
bookPrice,
purchaseDate,
isbn
}).save()
return newCustomer
},
updateCustomer: async (_, { _id, name, surname, email, phone, bookDescription, bookPrice, purchaseDate, isbn }, { Customer }) => {
const cust = await Customer.findOneAndUpdate(
{ _id: _id },
{
$set: {
name,
surname,
email,
phone,
bookDescription,
bookPrice,
purchaseDate,
isbn
}
},
{ new: true }
)
return cust
},
deleteCustomer: async (_, { _id }, { Customer }) => {
const cust = await Customer.findOneAndRemove({ _id: _id })
return cust
},
signInUser: async (_, { email, password }, { User }) => {
if (!User) {
throw new Error("User empty")
}
const user = await User.findOne({ email: email });
if (!user) {
throw new Error('User not found')
}
const isValidPassword = await bcrypt.compare(password, user.password)
if (!isValidPassword) {
throw new Error('Invalid password')
}
return { token: createToken(user, process.env.SECRET, '1hr') }
},
// (parent, args, context, info)
signUpUser: async (_, { name, surname, email, password }, { User }) => {
const user = await User.findOne({ email: email });
if (user) {
throw new Error('User already exists: ' + user);
}
const newUser = await new User({
name,
surname,
email,
password
}).save()
return { token: createToken(newUser, process.env.SECRET, '1hr') }
}
}
}