-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnote.ts
478 lines (436 loc) · 10.5 KB
/
note.ts
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
import type { FastifyPluginCallback } from 'fastify';
import type NoteService from '@domain/service/note.js';
import type NoteSettingsService from '@domain/service/noteSettings.js';
import type { ErrorResponse } from '@presentation/http/types/HttpResponse.js';
import type { Note, NotePublicId } from '@domain/entities/note.js';
import useNoteResolver from '../middlewares/note/useNoteResolver.js';
import useNoteSettingsResolver from '../middlewares/noteSettings/useNoteSettingsResolver.js';
import useMemberRoleResolver from '../middlewares/noteSettings/useMemberRoleResolver.js';
import { MemberRole } from '@domain/entities/team.js';
import { type NotePublic, definePublicNote } from '@domain/entities/notePublic.js';
import type NoteVisitsService from '@domain/service/noteVisits.js';
import EventBus from '@domain/event-bus/index.js';
import { NoteVisitedEvent } from '@domain/event-bus/events/noteVisitedEvent.js';
/**
* Interface for the note router.
*/
interface NoteRouterOptions {
/**
* Note service instance
*/
noteService: NoteService,
/**
* Note Settings service instance
*/
noteSettingsService: NoteSettingsService,
/**
* Note visits service instance
*/
noteVisitsService: NoteVisitsService;
}
/**
* Note router plugin
*
* @param fastify - fastify instance
* @param opts - empty options
* @param done - callback
*/
const NoteRouter: FastifyPluginCallback<NoteRouterOptions> = (fastify, opts, done) => {
/**
* Get note service from options
*/
const noteService = opts.noteService;
const noteSettingsService = opts.noteSettingsService;
/**
* Prepare note id resolver middleware
* It should be used in routes that accepts note public id
*/
const { noteResolver } = useNoteResolver(noteService);
/**
* Prepare note settings resolver middleware
* It should be used to use note settings in middlewares
*/
const { noteSettingsResolver } = useNoteSettingsResolver(noteSettingsService);
/**
* Prepare user role resolver middleware
* It should be used to use user role in middlewares
*/
const { memberRoleResolver } = useMemberRoleResolver(noteSettingsService);
/**
* Get note by id
*/
fastify.get<{
Params: {
notePublicId: NotePublicId;
},
Reply: {
note: NotePublic,
parentNote?: NotePublic | undefined,
accessRights: {
canEdit: boolean,
},
}| ErrorResponse,
}>('/:notePublicId', {
config: {
policy: [
'notePublicOrUserInTeam',
],
},
schema: {
params: {
notePublicId: {
$ref: 'NoteSchema#/properties/id',
},
},
response: {
'2xx': {
type: 'object',
properties: {
note: {
$ref: 'NoteSchema',
},
accessRights: {
type: 'object',
properties: {
canEdit: {
type: 'boolean',
},
},
},
parentNote: {
$ref: 'NoteSchema',
},
},
},
},
},
preHandler: [
noteResolver,
noteSettingsResolver,
memberRoleResolver,
],
}, async (request, reply) => {
const { note } = request;
const noteId = request.note?.id as number;
const { memberRole } = request;
const { userId } = request;
/**
* Check if note exists
*/
if (note === null) {
return reply.notFound('Note not found');
}
/**
* Check if user is authorized
*
* @todo use event bus to save note visits
*/
if (userId !== null) {
EventBus.getInstance().dispatch(new NoteVisitedEvent(noteId, userId));
}
const parentId = await noteService.getParentNoteIdByNoteId(note.id);
const parentNote = parentId !== null ? definePublicNote(await noteService.getNoteById(parentId)) : undefined;
/**
* Wrap note for public use
*/
const notePublic = definePublicNote(note);
/**
* Check if current user can edit the note
*/
const canEdit = memberRole === MemberRole.Write;
return reply.send({
note: notePublic,
parentNote: parentNote,
accessRights: { canEdit: canEdit },
});
});
/**
* Deletes note by id
*/
fastify.delete<{
Params: {
notePublicId: NotePublicId;
},
Reply: {
isDeleted: boolean
},
}>('/:notePublicId', {
schema: {
params: {
notePublicId: {
$ref: 'NoteSchema#/properties/id',
},
},
},
config: {
policy: [
'authRequired',
'userCanEdit',
],
},
preHandler: [
noteResolver,
],
}, async (request, reply) => {
const noteId = request.note?.id as number;
const isDeleted = await noteService.deleteNoteById(noteId);
/**
* Check if note does not exist
*/
return reply.send({ isDeleted : isDeleted });
});
/**
* Adds a new note.
* Responses with note public id.
*/
fastify.post<{
Body: {
content: JSON;
parentId?: NotePublicId;
},
Reply: {
id: NotePublicId,
},
}>('/', {
config: {
policy: [
'authRequired',
],
},
}, async (request, reply) => {
/**
* @todo Validate request query
*/
const content = request.body.content !== undefined ? request.body.content : {};
const { userId } = request;
const parentId = request.body.parentId;
const addedNote = await noteService.addNote(content as JSON, userId as number, parentId); // "authRequired" policy ensures that userId is not null
return reply.send({
id: addedNote.publicId,
});
});
/**
* Updates note by id.
*/
fastify.patch<{
Params: {
notePublicId: NotePublicId,
},
Body: {
content: JSON;
},
Reply: {
updatedAt: Note['updatedAt'],
}
}>('/:notePublicId', {
schema: {
params: {
notePublicId: {
$ref: 'NoteSchema#/properties/id',
},
},
body: {
content: {
$ref: 'NoteSchema#/properties/content',
},
},
},
config: {
policy: [
'authRequired',
'userCanEdit',
],
},
preHandler: [
noteResolver,
noteSettingsResolver,
],
}, async (request, reply) => {
const noteId = request.note?.id as number;
const content = request.body.content as JSON;
const note = await noteService.updateNoteContentById(noteId, content);
return reply.send({
updatedAt: note.updatedAt,
});
});
/**
* Update note relation by id.
*/
fastify.patch<{
Params: {
notePublicId: NotePublicId,
},
Body: {
parentNoteId: NotePublicId,
},
Reply: {
isUpdated: boolean,
}
}>('/:notePublicId/relation', {
schema: {
params: {
notePublicId: {
$ref: 'NoteSchema#/properties/id',
},
},
body: {
parentNoteId: {
$ref: 'NoteSchema#/properties/id',
},
},
response: {
'2xx': {
type: 'object',
properties: {
isUpdated: {
type: 'boolean',
},
},
},
},
},
config: {
policy: [
'authRequired',
'userCanEdit',
],
},
preHandler: [
noteResolver,
],
}, async (request, reply) => {
const noteId = request.note?.id as number;
const parentNoteId = request.body.parentNoteId;
const isUpdated = await noteService.updateNoteRelation(noteId, parentNoteId);
return reply.send({ isUpdated });
});
/**
* Delete parent relation
*/
fastify.delete<{
Params: {
notePublicId: NotePublicId,
},
Reply: {
isDeleted: boolean,
}
}>('/:notePublicId/relation', {
schema: {
params: {
notePublicId: {
$ref: 'NoteSchema#/properties/id',
},
},
response: {
'2xx': {
type: 'object',
properties: {
isDeleted: {
type: 'boolean',
},
},
},
},
},
config: {
policy: [
'authRequired',
'userCanEdit',
],
},
preHandler: [
noteResolver,
],
}, async (request, reply) => {
const noteId = request.note?.id as number;
const userId = request.note?.creatorId as number;
const isDeleted = await noteService.unlinkParent(noteId);
EventBus.getInstance().dispatch(new NoteVisitedEvent(noteId, userId));
/**
* Check if parent relation was successfully deleted
*/
if (!isDeleted) {
return reply.notAcceptable('Parent note does not exist');
}
return reply.send({ isDeleted });
});
/**
* Get note by custom hostname
*/
fastify.get<{
Params: {
/**
* Custom Hostname to search note by
*/
hostname: string;
},
Reply: {
note: NotePublic,
accessRights: {
canEdit: boolean,
},
}| ErrorResponse,
}>('/resolve-hostname/:hostname', {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
note: {
$ref: 'NoteSchema',
},
accessRights: {
type: 'object',
properties: {
canEdit: {
type: 'boolean',
},
},
},
},
},
},
},
}, async (request, reply) => {
const params = request.params;
const { userId } = request;
const note = await noteService.getNoteByHostname(params.hostname);
/**
* Check if note exists
*/
if (note === null) {
return reply.notFound('Note not found');
}
/**
* Save note visit if user is authorized
*
*/
if (userId !== null) {
EventBus.getInstance().dispatch(new NoteVisitedEvent(note.id, userId));
}
/**
* By default, unauthorized user can not edit the note
*/
let canEdit = false;
/**
* Wrapping Note for public use
*/
const notePublic = definePublicNote(note);
/**
* Check if current user is logged in and can edit the note
*/
if (request.userId !== null) {
const memberRole = await noteSettingsService.getUserRoleByUserIdAndNoteId(request.userId, note.id);
/**
* Check if current user can edit the note
*/
canEdit = memberRole === MemberRole.Write;
}
return reply.send({
note: notePublic,
accessRights: { canEdit: canEdit },
});
});
done();
};
export default NoteRouter;