-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote.service.ts
More file actions
90 lines (77 loc) · 2.53 KB
/
Copy pathnote.service.ts
File metadata and controls
90 lines (77 loc) · 2.53 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
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { Notes } from '../interfaces/notes';
@Injectable({
providedIn: 'root',
})
export class NoteService {
private notesSubject: BehaviorSubject<Notes[]> = new BehaviorSubject<Notes[]>(
this.loadFromStorage(),
);
public notes$: Observable<Notes[]> = this.notesSubject.asObservable();
constructor() {}
toggleFavourite(id: string): void {
const currentNotes = this.notesSubject.getValue();
const updated = currentNotes.map((note) =>
note.id === id
? { ...note, isFavourite: !note.isFavourite, updatedAt: new Date() }
: note,
);
this.notesSubject.next(updated);
this.saveToStorage(updated);
}
createNote(
note: Omit<Notes, 'id' | 'createdAt' | 'updatedAt' | 'isFavourite'>,
): void {
const newNote: Notes = {
...note,
id: this.generateId(),
isFavourite: false,
createdAt: new Date(),
updatedAt: new Date(),
};
const currentNotes = this.notesSubject.getValue();
const updated = [...currentNotes, newNote];
this.notesSubject.next(updated);
this.saveToStorage(updated);
}
updateNote(id: string, changes: Partial<Notes>): void {
const currentNotes = this.notesSubject.getValue();
const updated = currentNotes.map((note) =>
note.id === id ? { ...note, ...changes, updatedAt: new Date() } : note,
);
this.notesSubject.next(updated);
this.saveToStorage(updated);
}
deleteNote(id: string): void {
const currentNotes = this.notesSubject.getValue();
const updated = currentNotes.filter((note) => note.id !== id);
this.notesSubject.next(updated);
this.saveToStorage(updated);
}
getNoteById(id: string): Notes | undefined {
return this.notesSubject.getValue().find((note) => note.id === id);
}
getAllNotes(): Notes[] {
return this.notesSubject.getValue();
}
clearNotes(): void {
this.notesSubject.next([]);
localStorage.removeItem('notes');
}
private generateId(): string {
return crypto.randomUUID();
}
private getStorageKey(): string {
const stored = localStorage.getItem('currentUser');
const user = stored ? JSON.parse(stored) : null;
return user ? `notes_${user.id}` : 'notes_guest';
}
private saveToStorage(notes: Notes[]): void {
localStorage.setItem(this.getStorageKey(), JSON.stringify(notes));
}
private loadFromStorage(): Notes[] {
const stored = localStorage.getItem(this.getStorageKey());
return stored ? JSON.parse(stored) : [];
}
}