-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolvers.js
71 lines (64 loc) · 1.84 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
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const createToken = (user, secret, expiresIn) => {
const { username, email } = user
return jwt.sign({ username, email }, secret, { expiresIn })
}
module.exports = {
Query: {
getCurrentUser: async (_, args, { User, currentUser }) => {
if (!currentUser) return null
return User.findOne({
username: currentUser.username
}).populate({
path: 'favorites',
model: 'Post',
})
},
getUser: () => null,
getPosts: async (_, args, { Post }) => {
const posts = await Post.find({})
.sort({ createdDate: 'desc' })
.populate({
path: 'createdBy',
model: 'User'
})
return posts
}
},
Mutation: {
addPost: async (_, { title, imageUrl, categories, description, creatorId }, { Post }) => {
const newPost = await new Post({
title,
imageUrl,
categories,
description,
createdBy: creatorId
}).save()
return newPost
},
signupUser: async (_, { username, email, password }, { User }) => {
const user = await User.findOne({ username })
if (user) {
throw new Error(`User already exists ${user._id}`)
}
const newUser = await new User({
username,
email,
password
}).save()
return { token: createToken(newUser, process.env.SECRET, '1hr') }
},
signinUser: async (_, { username, password }, { User }) => {
const user = await User.findOne({ username })
if (!user) {
throw new Error(`User not found`)
}
const authenticated = await bcrypt.compareSync(password, user.password)
if (!authenticated) {
throw new Error(`Invalid password`)
}
return { token: createToken(user, process.env.SECRET, '1hr') }
},
}
}