-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolvers.js
More file actions
64 lines (61 loc) · 1.61 KB
/
resolvers.js
File metadata and controls
64 lines (61 loc) · 1.61 KB
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
import User from "./models/User";
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { APP_SECRET, getUserId } from './utils';
import { AuthenticationError } from "apollo-server";
const authenticated = next => (root, args, ctx, info) => {
if (!ctx.currentUser) {
throw new AuthenticationError("You must be logged in!");
}
return next(root, args, ctx, info)
}
const resolvers = {
Mutation: {
deleteUser: authenticated(async (_, args, ctx) => {
const deletedUser = await User.findOneAndDelete({ _id: args.userId }).exec();
return deletedUser
}),
createUser: (async (_, args, ctx) => {
const password = await bcrypt.hash(args.password, 10);
const user = await new User({ ...args, password }).save();
const token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + 60 * 60,
userId: user.id
},
APP_SECRET
)
return {
token,
user
};
}),
login: (async (_, args, ctx) => {
const user = await User.findOne({ username: args.username });
if (!user) {
throw new Error("User does not exist!");
}
const valid = await bcrypt.compare(args.password, user.password);
if (!valid) {
throw new Error("Invalid password");
}
const token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + 60 * 60,
userId: user.id
},
APP_SECRET
)
return {
token,
user
}
})
},
Query: {
users(_, args, ctx, info) {
return User.find({});
}
}
};
export default resolvers;