-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnoteVisits.ts
More file actions
69 lines (61 loc) · 2.29 KB
/
noteVisits.ts
File metadata and controls
69 lines (61 loc) · 2.29 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
import type { NoteInternalId } from '@domain/entities/note.js';
import type User from '@domain/entities/user.js';
import type NoteVisit from '@domain/entities/noteVisit.js';
import type NoteVisitsRepository from '@repository/noteVisits.repository.js';
import EventBus from '@domain/event-bus/index.js';
import { NOTE_ADDED_EVENT_NAME } from '@domain/event-bus/events/noteAddedEvent.js';
import { NOTE_VISITED_EVENT_NAME } from '@domain/event-bus/events/noteVisitedEvent.js';
/**
* Note Visits service, which will store latest note visit
* it is used to display recent notes for each user
*/
export default class NoteVisitsService {
/**
* Note Visits repository
*/
public noteVisitsRepository: NoteVisitsRepository;
/**
* NoteVisits service constructor
*
* @param noteVisitRepository - note Visits repository
*/
constructor(noteVisitRepository: NoteVisitsRepository) {
this.noteVisitsRepository = noteVisitRepository;
/**
* Listen to the note related events
*/
EventBus.getInstance().addEventListener(NOTE_ADDED_EVENT_NAME, async (event) => {
const { noteId, userId } = (event as CustomEvent<{ noteId: number; userId: number }>).detail;
try {
return await this.noteVisitsRepository.saveVisit(noteId, userId);
} catch (error) {
throw error;
}
});
EventBus.getInstance().addEventListener(NOTE_VISITED_EVENT_NAME, async (event) => {
const { noteId, userId } = (event as CustomEvent<{ noteId: number; userId: number }>).detail;
try {
await this.noteVisitsRepository.saveVisit(noteId, userId);
} catch (error) {
console.error('Error saving note visit', error);
}
});
}
/**
* Updates existing noteVisit's visitedAt or creates new record if user opens note for the first time
*
* @param noteId - note internal id
* @param userId - id of the user
*/
public async saveVisit(noteId: NoteInternalId, userId: User['id']): Promise<NoteVisit> {
return await this.noteVisitsRepository.saveVisit(noteId, userId);
};
/**
* Deletes all visits of the note when a note is deleted
*
* @param noteId - note internal id
*/
public async deleteNoteVisits(noteId: NoteInternalId): Promise<boolean> {
return await this.noteVisitsRepository.deleteNoteVisits(noteId);
}
}