forked from codex-team/notes.api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote.ts
More file actions
523 lines (436 loc) · 16.5 KB
/
note.ts
File metadata and controls
523 lines (436 loc) · 16.5 KB
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
import type { Note, NoteContent, NoteInternalId, NotePublicId } from '@domain/entities/note.js';
import type NoteRepository from '@repository/note.repository.js';
import type NoteVisitsRepository from '@repository/noteVisits.repository.js';
import { createPublicId } from '@infrastructure/utils/id.js';
import { DomainError } from '@domain/entities/DomainError.js';
import type NoteRelationsRepository from '@repository/noteRelations.repository.js';
import type EditorToolsRepository from '@repository/editorTools.repository.js';
import type User from '@domain/entities/user.js';
import type { NoteList } from '@domain/entities/noteList.js';
import type NoteHistoryRepository from '@repository/noteHistory.repository.js';
import type { NoteHistoryMeta, NoteHistoryRecord, NoteHistoryPublic } from '@domain/entities/noteHistory.js';
import type { NoteHierarchy } from '@domain/entities/NoteHierarchy.js';
/**
* Note service
*/
export default class NoteService {
/**
* Note repository
*/
public noteRepository: NoteRepository;
/**
* Note relationship repository
*/
public noteRelationsRepository: NoteRelationsRepository;
/**
* Note visits repository
*/
public noteVisitsRepository: NoteVisitsRepository;
/**
* Edtor tools repository
*/
public editorToolsRepository: EditorToolsRepository;
/**
* Note history repository
*/
public noteHistoryRepository: NoteHistoryRepository;
/**
* Number of the notes to be displayed on one page
* it is used to calculate offset and limit for getting notes that the user has recently opened
*/
private readonly noteListPortionSize = 30;
/**
* Constant used for checking that content changes are valuable enough to save updated note content to the history
*/
private readonly valuableContentChangesLength = 100;
/**
* Note service constructor
* @param noteRepository - note repository
* @param noteRelationsRepository - note relationship repository
* @param noteVisitsRepository - note visits repository
* @param editorToolsRepository - editor tools repositoryn
* @param noteHistoryRepository - note history repository
*/
constructor(noteRepository: NoteRepository, noteRelationsRepository: NoteRelationsRepository, noteVisitsRepository: NoteVisitsRepository, editorToolsRepository: EditorToolsRepository, noteHistoryRepository: NoteHistoryRepository) {
this.noteRepository = noteRepository;
this.noteRelationsRepository = noteRelationsRepository;
this.noteVisitsRepository = noteVisitsRepository;
this.editorToolsRepository = editorToolsRepository;
this.noteHistoryRepository = noteHistoryRepository;
}
/**
* Adds note
* @param content - note content
* @param creatorId - note creator
* @param parentPublicId - parent note if exist
* @param tools - editor tools that were used in a note content
* @returns added note object
*/
public async addNote(content: Note['content'], creatorId: Note['creatorId'], parentPublicId: Note['publicId'] | undefined, tools: Note['tools']): Promise<Note> {
const note = await this.noteRepository.addNote({
publicId: createPublicId(),
content,
creatorId,
tools,
});
/**
* First note save always goes to the note history
*/
await this.noteHistoryRepository.createNoteHistoryRecord({
content,
userId: creatorId,
noteId: note.id,
tools,
});
if (parentPublicId !== undefined) {
const parentNote = await this.getNoteByPublicId(parentPublicId);
if (parentNote === null) {
throw new DomainError(`Incorrect parent note`);
}
await this.noteRelationsRepository.addNoteRelation(note.id, parentNote.id);
}
return note;
}
/**
* @todo Build a note tree and delete all descendants of a deleted note
*/
/**
* Deletes note by id
* @param id - note internal id
*/
public async deleteNoteById(id: NoteInternalId): Promise<boolean> {
/**
* @todo If the note has not been deleted,
* we must reset the note_relations database to its original state
*/
const hasRelation = await this.noteRelationsRepository.hasRelation(id);
if (hasRelation) {
const isNoteRelationsDeleted = await this.noteRelationsRepository.deleteNoteRelationsByNoteId(id);
if (isNoteRelationsDeleted === false) {
throw new DomainError(`Relation with noteId ${id} was not deleted`);
}
}
/**
* Delete all note history records on note deletion
*/
await this.noteHistoryRepository.deleteNoteHistoryByNoteId(id);
const isNoteDeleted = await this.noteRepository.deleteNoteById(id);
if (isNoteDeleted === false) {
throw new DomainError(`Note with id ${id} was not deleted`);
}
return isNoteDeleted;
}
/**
* Updates a note
* @param id - note internal id
* @param content - new content
* @param noteTools - tools which are used in note
* @param userId - id of the user that made changes
*/
public async updateNoteContentAndToolsById(id: NoteInternalId, content: Note['content'], noteTools: Note['tools'], userId: User['id']): Promise<Note> {
/**
* If content changes are valuable, they will be saved to note history
*/
if (await this.areContentChangesSignificant(id, content)) {
await this.noteHistoryRepository.createNoteHistoryRecord({
content,
userId: userId,
noteId: id,
tools: noteTools,
});
};
const updatedNote = await this.noteRepository.updateNoteContentAndToolsById(id, content, noteTools);
if (updatedNote === null) {
throw new DomainError(`Note with id ${id} was not updated`);
}
return updatedNote;
}
/**
* Unlink parent note from the current note
* @param noteId - id of note to unlink parent
*/
public async unlinkParent(noteId: NoteInternalId): Promise<boolean> {
return this.noteRelationsRepository.unlinkParent(noteId);
}
/**
* Returns note by id
* @param id - note internal id
*/
public async getNoteById(id: NoteInternalId): Promise<Note> {
const note = await this.noteRepository.getNoteById(id);
if (note === null) {
throw new DomainError(`Note with id ${id} was not found`);
}
return note;
}
/**
* Returns note by public id
* @param publicId - note public id
*/
public async getNoteByPublicId(publicId: NotePublicId): Promise<Note> {
const note = await this.noteRepository.getNoteByPublicId(publicId);
if (note === null) {
throw new DomainError(`Note with public id ${publicId} was not found`);
}
return note;
}
/**
* Gets note by custom hostname
* @param hostname - hostname
* @returns note
*/
public async getNoteByHostname(hostname: string): Promise<Note | null> {
return await this.noteRepository.getNoteByHostname(hostname);
}
/**
* Get parent note id by note id
* @param noteId - id of the current note
*/
public async getParentNoteIdByNoteId(noteId: NoteInternalId): Promise<NoteInternalId | null> {
return await this.noteRelationsRepository.getParentNoteIdByNoteId(noteId);
}
/**
* Returns note list by creator id
* @param userId - id of the user
* @param page - number of current page
* @returns list of the notes ordered by time of last visit
*/
public async getNoteListByUserId(userId: User['id'], page: number): Promise<NoteList> {
const offset = (page - 1) * this.noteListPortionSize;
return {
items: await this.noteRepository.getNoteListByUserId(userId, offset, this.noteListPortionSize),
};
}
/**
* Create note relation
* @param noteId - id of the current note
* @param parentPublicId - id of the parent note
*/
public async createNoteRelation(noteId: NoteInternalId, parentPublicId: NotePublicId): Promise<Note> {
const currenParentNote = await this.noteRelationsRepository.getParentNoteIdByNoteId(noteId);
/**
* Check if the note already has a parent
*/
if (currenParentNote !== null) {
throw new DomainError(`Note already has parent note`);
}
const parentNote = await this.noteRepository.getNoteByPublicId(parentPublicId);
if (parentNote === null) {
throw new DomainError(`Incorrect parent note Id`);
}
let parentNoteId: number | null = parentNote.id;
/**
* This loop checks for cyclic reference when updating a note's parent.
*/
while (parentNoteId !== null) {
if (parentNoteId === noteId) {
throw new DomainError(`Forbidden relation. Note can't be a child of own child`);
}
parentNoteId = await this.noteRelationsRepository.getParentNoteIdByNoteId(parentNoteId);
}
const isCreated = await this.noteRelationsRepository.addNoteRelation(noteId, parentNote.id);
if (!isCreated) {
throw new DomainError(`Relation was not created`);
}
return parentNote;
}
/**
* Update note relation
* @param noteId - id of the current note
* @param parentPublicId - id of the new parent note
*/
public async updateNoteRelation(noteId: NoteInternalId, parentPublicId: NotePublicId): Promise<boolean> {
const parentNote = await this.noteRepository.getNoteByPublicId(parentPublicId);
if (parentNote === null) {
throw new DomainError(`Incorrect parent note`);
}
let parentNoteId: number | null = parentNote.id;
/**
* This loop checks for cyclic reference when updating a note's parent.
*/
while (parentNoteId !== null) {
if (parentNoteId === noteId) {
throw new DomainError(`Forbidden relation. Note can't be a child of own child`);
}
parentNoteId = await this.noteRelationsRepository.getParentNoteIdByNoteId(parentNoteId);
}
return await this.noteRelationsRepository.updateNoteRelationById(noteId, parentNote.id);
};
/**
* Raise domain error if tools, that are in note content are not specified in tools array
* @param tools - editor tools that were used in a note content
* @param content - content of the note
* @todo validate tool ids
*/
public async validateNoteTools(tools: Note['tools'], content: Note['content'] | Record<string, never>): Promise<void> {
/**
* Set of the tools that are used in note
*/
const toolsInContent = Array.from(new Set(content.blocks.map(block => block.type)));
/**
* Tools that are specified in tools array
*/
const passedToolsNames = tools.map(tool => tool.name);
const passedToolsIds = tools.map(tool => tool.id);
/**
* Check that all tools used in note are specified in toolsInContent array
*/
const toolsAreSpicified = toolsInContent.every((toolName) => {
return passedToolsNames.includes(toolName);
});
if (!toolsAreSpicified) {
throw new DomainError('Incorrect tools passed');
}
/**
* Extra tools specified
*/
if (tools.length !== toolsInContent.length) {
throw new DomainError('Incorrect tools passed');
}
/**
* Validate tool ids
*/
try {
await this.editorToolsRepository.getToolsByIds(passedToolsIds);
} catch {
throw new DomainError('Incorrect tools passed');
}
}
/**
* Get note public id by it's internal id
* Used for making entities that use NoteInternalId public
* @param id - internal id of the note
* @returns note public id
*/
public async getNotePublicIdByInternal(id: NoteInternalId): Promise<NotePublicId> {
const note = await this.noteRepository.getNoteById(id);
if (note === null) {
throw new DomainError(`Note with id ${id} was not found`);
}
return note.publicId;
}
/**
* Check if content changes are valuable enough to save currently changed note to the history
* The sufficiency of changes is determined by the length of the content change
* @param noteId - id of the note that is currently changed
* @param content - updated note content
* @returns - boolean, true if changes are valuable enough, false otherwise
*/
public async areContentChangesSignificant(noteId: NoteInternalId, content: Note['content']): Promise<boolean> {
const currentlySavedNoteContent = (await this.noteHistoryRepository.getLastContentVersion(noteId));
if (currentlySavedNoteContent === undefined) {
throw new DomainError('No history for the note found');
}
const currentContentLength = currentlySavedNoteContent.blocks.reduce((length, block) => {
length += JSON.stringify(block.data).length;
return length;
}, 0);
const patchedContentLength = content.blocks.reduce((length, block) => {
length += JSON.stringify(block.data).length;
return length;
}, 0);
if (Math.abs(currentContentLength - patchedContentLength) >= this.valuableContentChangesLength) {
return true;
}
return false;
}
/**
* Get all note content change history metadata (without actual content)
* Used for preview of all changes of the note content
* @param noteId - id of the note
* @returns - array of metadata of note changes history
*/
public async getNoteHistoryByNoteId(noteId: Note['id']): Promise<NoteHistoryMeta[]> {
return await this.noteHistoryRepository.getNoteHistoryByNoteId(noteId);
}
/**
* Get concrete history record of the note
* Used for showing some of the note content versions
* @param id - id of the note history record
* @returns full public note history record with user information or raises domain error if record not found
*/
public async getHistoryRecordById(id: NoteHistoryRecord['id']): Promise<NoteHistoryPublic> {
const noteHistoryRecord = await this.noteHistoryRepository.getHistoryRecordById(id);
if (noteHistoryRecord === null) {
throw new DomainError('This version of the note not found');
}
/**
* Resolve note history record for it to be public
* changes noteId from internal to public
*/
const noteHistoryPublic = {
id: noteHistoryRecord.id,
noteId: await this.getNotePublicIdByInternal(noteHistoryRecord.noteId),
userId: noteHistoryRecord.userId,
content: noteHistoryRecord.content,
tools: noteHistoryRecord.tools,
createdAt: noteHistoryRecord.createdAt,
user: noteHistoryRecord.user,
};
return noteHistoryPublic;
}
/**
* Return a sequence of parent notes for the given note id.
* @param noteId - id of the note to get parent structure
* @returns - array of notes that are parent structure of the note
*/
public async getNoteParents(noteId: NoteInternalId): Promise<Note[]> {
const noteIds: NoteInternalId[] = await this.noteRelationsRepository.getNoteParentsIds(noteId);
const noteParents = await this.noteRepository.getNotesByIds(noteIds);
return noteParents;
}
/**
* Reutrn a tree structure of notes with childNotes for the given note id
* @param noteId - id of the note to get structure
* @returns - Object of notes.
*/
public async getNoteHierarchy(noteId: NoteInternalId): Promise<NoteHierarchy | null> {
const ultimateParent = await this.noteRelationsRepository.getUltimateParentNoteId(noteId);
// If there is no ultimate parent, the provided noteId is the ultimate parent
const rootNoteId = ultimateParent ?? noteId;
const notesRows = await this.noteRepository.getNoteDAOByNoteId(rootNoteId);
const notesMap = new Map<NoteInternalId, NoteHierarchy>();
let root: NoteHierarchy | null = null;
if (!notesRows || notesRows.length === 0) {
return null;
}
// Step 1: Parse and initialize all notes
notesRows.forEach((note) => {
notesMap.set(note.noteId, {
noteId: note.publicId,
noteTitle: this.getTitleFromContent(note.content),
childNotes: null,
});
});
// Step 2: Build hierarchy
notesRows.forEach((note) => {
if (note.parentId === null) {
root = notesMap.get(note.noteId) ?? null;
} else {
const parent = notesMap.get(note.parentId);
if (parent) {
// Initialize childNotes as an array if it's null
if (parent.childNotes === null) {
parent.childNotes = [];
}
parent.childNotes?.push(notesMap.get(note.noteId)!);
}
}
});
return root;
}
/**
* Get the title of the note
* @param content - content of the note
* @returns the title of the note
*/
public getTitleFromContent(content: NoteContent): string {
const limitCharsForNoteTitle = 50;
const firstNoteBlock = content.blocks[0];
const text = (firstNoteBlock?.data as { text?: string })?.text;
if (text === undefined || text.trim() === '') {
return 'Untitled';
}
return text.replace(/ /g, ' ').slice(0, limitCharsForNoteTitle);
};
}