Quick actions

cmd+k|ctrl+k

Navigation

Languages

localStorage service

Snippet info

Language

TypeScript

Visibility

public

Author

paulkotov

Created

2019-10-31T22:11:38Z

Updated

2019-11-01T09:54:46Z

export interface Note {
  [elementId: string]: {
    title: string;
    text: string;
    isLiked: boolean;
  };
}

export class StorageService {
  public static initService () {
    if (!StorageService.getNotes().length) {
      Array
        .from(Array(5).keys())
        .forEach(() => {
          StorageService.addNote({
            id: faker.random.uuid(),
            title: faker.random.word(),
            text: faker.lorem.paragraph(),
            isLiked: false
          });
        });
    }
  }

  public static addNote (data: Note): void {
    const saved = StorageService.getNotes();
    saved[id] = data;
    
    StorageService.saveNotes(saved);
  }

  public static editNote (id: string, data: Partial<Note>): void {
    let savedNotes = StorageService.getNotes();
    savedNotes[id] = {
        ...savedNotes[id],
        ...data
    };
    StorageService.saveNotes(savedNotes);
  }

  public static removeNote (id: string): void {
    const savedNotes = StorageService.getNotes();
    delete savedNotes[id]
    StorageService.saveNotes(newNotes);
  }

  public static getNotes (): Note[] {
    const result = JSON.parse(localStorage.getItem('notes'));
    return result || {};
  }

  public static saveNotes (Notes: Note[]) {
    localStorage.setItem('Notes', JSON.stringify(Notes));
  }

  public static findNote (id: string) {
    return StorageService.getNotes()[id];
  }

  public static toggleLikeToNote (id: string): void {
    const savedNotes = StorageService.getNotes();
    savedNodes[id][isLiked] = !savedNodes[id][isLiked];
    StorageService.saveNotes(savedNotes);
  }
}
INFO