-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolvers.js
76 lines (67 loc) · 1.91 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
import { quotes,users } from "./fakedb.js";
import {randomBytes} from "crypto";
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken"
const User=mongoose.model("User");
const Quote=mongoose.model("Quote")
const resolvers={
Query:{
users:async ()=> await User.find({}),
user:async (_,{_id})=> await User.findOne({_id}),
quotes:async ()=>await Quote.find({}).populate("by","_id firstName"),
ind_quote:async (_,{by})=> await Quote.find({by}),
myprofile:async (_,args,{userId})=>{
if(!userId) throw new Error("You must be logged in")
return await User.findOne({_id:userId})
}
},
User:
{
quotes:async(Ur)=>await Quote.find({by:Ur._id})
},
Mutation:
{
signupUser:async(_,{userNew})=>{
const user= await User.findOne({email:userNew.email})
if(user)
{
throw new Error("User already exists with that email")
}
const hashedPassword= await bcrypt.hash(userNew.password,12)
const newUser= new User({
...userNew,
password:hashedPassword
})
return await newUser.save()
},
signinUser:async(_,{userSignin})=>{
const user=await User.findOne({email:userSignin.email})
if(!user)
{
throw new Error("User doesn't exists with that email")
}
const doMatch= await bcrypt.compare(userSignin.password,user.password)
if(!doMatch)
{
throw new Error("email or password is invalid")
}
const token=jwt.sign({userId:user._id},process.env.JWT_SECRET)
return {token}
},
createQuote:async(_,{name},{userId})=>{
//user only create qutoe when logged in
if(!userId)
{
throw new Error("You must be logged In")
}
const newQuote= new Quote({
name,
by:userId
})
await newQuote.save()
return "Quote saved successfully"
}
}
}
export default resolvers;