-
Notifications
You must be signed in to change notification settings - Fork 303
/
Copy pathindex.js
103 lines (94 loc) · 2.49 KB
/
index.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
97
98
99
100
101
102
103
const bcrypt = require('bcryptjs');
const Event = require('../../models/event');
const User = require('../../models/user');
const events = async eventIds => {
try {
const events = await Event.find({ _id: { $in: eventIds } });
events.map(event => {
return {
...event._doc,
_id: event.id,
date: new Date(event._doc.date).toISOString(),
creator: user.bind(this, event.creator)
};
});
return events;
} catch (err) {
throw err;
}
};
const user = async userId => {
try {
const user = await User.findById(userId);
return {
...user._doc,
_id: user.id,
createdEvents: events.bind(this, user._doc.createdEvents)
};
} catch (err) {
throw err;
}
};
module.exports = {
events: async () => {
try {
const events = await Event.find();
return events.map(event => {
return {
...event._doc,
_id: event.id,
date: new Date(event._doc.date).toISOString(),
creator: user.bind(this, event._doc.creator)
};
});
} catch (err) {
throw err;
}
},
createEvent: async args => {
const event = new Event({
title: args.eventInput.title,
description: args.eventInput.description,
price: +args.eventInput.price,
date: new Date(args.eventInput.date),
creator: '5c0fbd06c816781c518e4f3e'
});
let createdEvent;
try {
const result = await event.save();
createdEvent = {
...result._doc,
_id: result._doc._id.toString(),
date: new Date(event._doc.date).toISOString(),
creator: user.bind(this, result._doc.creator)
};
const creator = await User.findById('5c0fbd06c816781c518e4f3e');
if (!creator) {
throw new Error('User not found.');
}
creator.createdEvents.push(event);
await creator.save();
return createdEvent;
} catch (err) {
console.log(err);
throw err;
}
},
createUser: async args => {
try {
const existingUser = await User.findOne({ email: args.userInput.email });
if (existingUser) {
throw new Error('User exists already.');
}
const hashedPassword = await bcrypt.hash(args.userInput.password, 12);
const user = new User({
email: args.userInput.email,
password: hashedPassword
});
const result = await user.save();
return { ...result._doc, password: null, _id: result.id };
} catch (err) {
throw err;
}
}
};