-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolvers.js
560 lines (449 loc) · 16.6 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/**
* This file defines the functions that will be used to query or modify
* some data in MongoDB.
*/
import { AuthenticationError, ForbiddenError, UserInputError } from 'apollo-server-express';
import bcrypt from 'bcrypt';
import mongoose from 'mongoose';
import User from './models/user';
import Database, { DatabaseViews } from './models/database';
import Note from './models/note';
import Category from './models/category';
import SharedLink from './models/sharedLink';
// NOTE: We use email as the unique id for user
const resolvers = {
Query: {
getNote: async (parent, { noteId }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
return await Note.findById(noteId);
},
getDatabase: async (parent, { databaseId }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const databaseDocument = await Database.findOne({ _id: databaseId })
.populate('notes')
.populate('categories');
return databaseDocument;
},
getAllUserDatabases: async (parent, args, context) => {
assertAuthenticated(context);
const email = context.getUser().email;
const userDocument = await User.findOne({ email: email }).populate('databases');
return userDocument.databases;
},
currentUser: (parent, { args }, context) => context.getUser(),
getNoteBySharedLinkHash: async (parent, { hash }, context) => {
// Note: there is no auth required for shared links (design decision)
const sharedLink = await SharedLink.findOne({ hash });
const note = await Note.findOne({ _id: sharedLink.noteId }).populate('user');
return note;
}
},
Mutation: {
// ================== Authentication related ==================
login: async (parent, { email, password }, context) => {
// TODO: Handle authentication failure
const { user } = await context.authenticate('graphql-local', { email, password });
await context.login(user);
console.log(context.getUser());
return { user };
},
logout: (parent, args, context) => context.logout(),
register: async (root, { input }, context) => {
if (await User.findOne({ email: input.email })) {
throw new UserInputError('Email has been taken');
}
const newDatabase = await new Database({
// TODO: Double check defaults
title: input.firstname + ' ' + input.lastname + "'s first database",
currentView: DatabaseViews.BOARD,
notes: [],
categories: []
}).save();
const newCategory = await new Category({
name: 'Non-categorised',
notes: [],
databaseId: newDatabase._id
}).save();
newDatabase.categories.push(newCategory._id);
await newDatabase.save();
const newUser = new User({
firstname: input.firstname,
lastname: input.lastname,
email: input.email,
password: input.password,
databases: [newDatabase._id],
lastVisited: newDatabase._id
});
await newUser.hashPassword();
newUser.save((error, document) => {
// TODO: Remove this console log
if (error) console.error(error);
console.log(document);
});
await context.login(newUser);
console.log(newUser);
return { user: newUser };
},
// ================== Database related ==================
// TODO: Handle the ordering of the databases
createDatabase: async (parent, { index, title }, context) => {
assertAuthenticated(context);
const email = context.getUser().email;
const userDocument = await User.findOne({ email: email });
const newDatabase = await new Database({
// TODO: Double check defaults
title: title,
currentView: DatabaseViews.BOARD,
notes: [],
categories: []
}).save();
const newCategory = await new Category({
name: 'Non-categorised',
notes: [],
databaseId: newDatabase._id
}).save();
newDatabase.categories.push(newCategory._id);
await newDatabase.save();
userDocument.databases.splice(index, 0, newDatabase._id);
await userDocument.save();
// TODO: Check whether to return a boolean instead
return newDatabase;
},
deleteDatabase: async (parent, { databaseId }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const deletedDatabase = await Database.findOneAndRemove(
{ _id: databaseId },
{
useFindAndModify: false
}
);
const email = context.getUser().email;
const userDocument = await User.findOne({ email: email });
arrayRemoveItem(userDocument.databases, databaseId);
await userDocument.save();
return deletedDatabase;
},
updateDatabaseTitle: async (parent, { databaseId, title }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
return await Database.findOneAndUpdate(
{ _id: databaseId },
{ title: title },
{
new: true,
useFindAndModify: false
}
);
},
updateDatabaseView: async (parent, { databaseId, view }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
return await Database.findOneAndUpdate(
{ _id: databaseId },
{ currentView: view },
{
new: true,
useFindAndModify: false
}
);
},
updateDatabaseNotes: async (parent, { databaseId, notes }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
return await Database.findOneAndUpdate(
{ _id: databaseId },
{ notes: notes },
{
new: true,
useFindAndModify: false
}
);
},
updateDatabases: async (parent, { databases }, context) => {
assertAuthenticated(context);
const email = context.getUser().email;
const userDocument = await User.findOne({ email: email });
userDocument.databases = databases;
userDocument.save();
return userDocument;
},
updateLastVisited: async (parent, { lastVisited }, context) => {
assertAuthenticated(context);
const email = context.getUser().email;
const userDocument = await User.findOne({ email: email });
userDocument.lastVisited = lastVisited;
userDocument.save();
return userDocument;
},
// TODO: updateDatabaseNotes (array of IDs)
// ================== Note related ==================
// TODO: Handle the ordering of the notes
createNote: async (parent, { databaseId, categoryId, title, index }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const databaseDocument = await Database.findOne({ _id: databaseId });
const newNote = await new Note({
// TODO: Double check defaults
userId: context.getUser()._id,
databaseId: databaseId,
categoryId: categoryId,
title: title,
blocks: []
}).save();
const categoryDocument = await Category.findOne({ _id: categoryId });
const noteCopy = [...categoryDocument.notes];
if (databaseDocument.currentView === DatabaseViews.BOARD) {
databaseDocument.notes.push(newNote._id);
await databaseDocument.save();
noteCopy.splice(index, 0, newNote._id);
} else if (databaseDocument.currentView === DatabaseViews.TABLE) {
// Assumes that categoryDocument passed in is the first category
databaseDocument.notes.splice(index, 0, newNote._id);
await databaseDocument.save();
noteCopy.push(newNote._id);
} else {
throw new UserInputError('There is no such database view!');
}
await Category.findOneAndUpdate(
{ _id: categoryId },
{ notes: noteCopy },
{
new: true,
useFindAndModify: false
}
);
// TODO: Check whether to return a boolean instead
return newNote;
},
deleteNote: async (parent, { noteId }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
const noteDocument = await Note.findOne({ _id: noteId });
const databaseId = noteDocument.databaseId;
const categoryId = noteDocument.categoryId;
await Note.findOneAndRemove(
{ _id: noteId },
{
useFindAndModify: false
}
);
const databaseDocument = await Database.findOne({ _id: databaseId });
arrayRemoveItem(databaseDocument.notes, noteId);
await databaseDocument.save();
const categoryDocument = await Category.findOne({ _id: categoryId });
arrayRemoveItem(categoryDocument.notes, noteId);
await categoryDocument.save();
return noteDocument;
},
deleteDatabaseCategory: async (parent, { databaseId, categoryId }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const databaseDocument = await Database.findOne({ _id: databaseId });
const categoryDocument = await Category.findOne({ _id: categoryId });
await Note.deleteMany({
_id: {
$in: categoryDocument.notes
}
});
categoryDocument.notes.forEach(note => {
arrayRemoveItem(databaseDocument.notes, note);
});
arrayRemoveItem(databaseDocument.categories, categoryDocument._id);
await databaseDocument.save();
await Category.findOneAndRemove(
{ _id: categoryId },
{
userFindAndModify: false
}
);
return databaseDocument;
},
updateDatabaseCategories: async (parent, { databaseId, categories }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const databaseDocument = await Database.findOne({ _id: databaseId });
databaseDocument.categories = categories;
await databaseDocument.save();
return databaseDocument;
},
updateCategoryName: async (parent, { categoryId, name }, context) => {
assertAuthenticated(context);
const categoryDocument = await Category.findOne({ _id: categoryId });
await verifyDatabaseBelongsToUser(context, categoryDocument.databaseId);
categoryDocument.name = name;
await categoryDocument.save();
return categoryDocument;
},
createDatabaseCategory: async (parent, { databaseId, categoryName, index }, context) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const newCategory = await new Category({
name: categoryName,
notes: [],
databaseId: databaseId
}).save();
const databaseDocument = await Database.findOne({ _id: databaseId });
if (databaseDocument.currentView === DatabaseViews.BOARD) {
databaseDocument.categories.splice(index, 0, newCategory.id);
} else if (databaseDocument.currentView === DatabaseViews.TABLE) {
databaseDocument.categories.push(newCategory.id);
} else {
throw new UserInputError('There is no such database view!');
}
await databaseDocument.save();
return newCategory;
},
createDatabaseCategoryForCurrentNote: async (
parent,
{ databaseId, categoryName, noteId },
context
) => {
assertAuthenticated(context);
await verifyDatabaseBelongsToUser(context, databaseId);
const noteDocument = await Note.findOne({ _id: noteId });
const currentCategory = await Category.findOne({ _id: noteDocument.categoryId });
arrayRemoveItem(currentCategory.notes, noteId);
currentCategory.save();
const newCategory = await new Category({
name: categoryName,
notes: [noteId],
databaseId: databaseId
}).save();
noteDocument.categoryId = newCategory._id;
noteDocument.save();
const databaseDocument = await Database.findOne({ _id: databaseId });
databaseDocument.categories.push(newCategory.id);
await databaseDocument.save();
return databaseDocument;
},
updateNoteTitle: async (parent, { noteId, title }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
// TODO: Check deprecation warning
return await Note.findOneAndUpdate(
{ _id: noteId },
{ title: title, latestUpdate: Date.now() },
{
new: true,
useFindAndModify: false
}
);
},
updateNoteCategory: async (parent, { noteId, categoryId, index }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
const session = await mongoose.startSession();
let newCategoryDocument;
await session.withTransaction(async () => {
const noteDocument = await Note.findOne({ _id: noteId });
const currentCategoryDocument = await Category.findOne({ _id: noteDocument.categoryId });
arrayRemoveItem(currentCategoryDocument.notes, noteDocument._id);
await currentCategoryDocument.save();
newCategoryDocument = await Category.findOne({ _id: categoryId });
const databaseDocument = await Database.findOne({ _id: newCategoryDocument.databaseId });
// check currentview, to determine whether index will be used
if (databaseDocument.currentView === DatabaseViews.BOARD) {
newCategoryDocument.notes.splice(index, 0, noteDocument._id);
} else if (databaseDocument.currentView === DatabaseViews.TABLE) {
newCategoryDocument.notes.push(noteDocument._id);
} else {
throw new UserInputError('There is no such database view!');
}
await newCategoryDocument.save();
await Note.findOneAndUpdate(
{ _id: noteId },
{ categoryId: categoryId },
{
new: true,
useFindAndModify: false
}
);
});
session.endSession();
return await Database.findOne({ _id: newCategoryDocument.databaseId }).populate([
'notes',
'categories'
]);
},
updateNoteBlocks: async (parent, { noteId, input }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
// TODO: Check deprecation warning
return await Note.findOneAndUpdate(
{ _id: noteId },
{ ...input, latestUpdate: Date.now() },
{
new: true,
useFindAndModify: false
}
);
},
generateSharedLink: async (parent, { noteId }, context) => {
assertAuthenticated(context);
await verifyNoteBelongsToUser(context, noteId);
const existingLink = await SharedLink.findOne({ noteId: noteId });
if (existingLink) {
return existingLink;
} else {
const salt = await bcrypt.genSalt(12);
const hashedId = await bcrypt.hash(noteId, salt);
const link = new SharedLink({
noteId: noteId,
hash: hashedId
});
link.save();
return link;
}
}
// TODO: updateNoteDatabaseId (when shifting notes between databases)
}
};
/**
* Checks whether the user is logged in. Throws an AuthenticationError
* otherwise.
*/
const assertAuthenticated = context => {
if (!context.getUser()) {
throw new AuthenticationError('You need to be logged in');
}
};
/**
* Verifies that the specified database exists, and belongs to the
* current logged in user. Requires await.
*/
const verifyDatabaseBelongsToUser = async (context, databaseId) => {
const databaseDocument = await Database.findOne({ _id: databaseId });
if (!databaseDocument) {
throw new UserInputError('This database does not exist!');
}
if (!context.getUser().databases.includes(databaseId)) {
throw new ForbiddenError('This database does not belong to you!');
}
};
/**
* Verifies that the specified note exists, and belongs to the
* current logged in user. Requires await.
*/
const verifyNoteBelongsToUser = async (context, noteId) => {
const noteDocument = await Note.findOne({ _id: noteId });
if (!noteDocument) {
throw new UserInputError('Note does not exist!');
}
if (noteDocument.userId.toString() !== context.getUser()._id.toString()) {
throw new ForbiddenError('This note does not belong to you!');
}
};
/**
* In-place removal of the specified item from the given array
* if it exists.
*/
const arrayRemoveItem = (arr, value) => {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
};
export default resolvers;