123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- const {ipcRenderer} = require('electron');
- class DataService {
- constructor() {
- // Load data from files
- if (!localStorage.list) {
- this.__load();
- }
- }
- get data() {
- const result = [];
- const list = JSON.parse(localStorage.list);
- for (const element of list) {
- result.push(JSON.parse(localStorage.getItem(element)));
- }
- return result;
- }
- getById(id) {
- const list = JSON.parse(localStorage.list);
- if (list.indexOf(id) !== -1) {
- return JSON.parse(localStorage.getItem(id));
- }
- return null;
- }
- add(id, title, content) {
- // If no id (param id = title and param title = content)
- if (!content) {
- content = title;
- title = id;
- // Generate id
- id = this.__uniqid();
- }
- // Add in list
- const list = JSON.parse(localStorage.list);
- list.push(id);
- localStorage.setItem('list', JSON.stringify(list));
- // Add data
- this.update(id, title, content);
- }
- update(id, title, content) {
- // Set object
- const data = {
- id: id,
- title: title,
- content: content
- }
- // Save
- localStorage.setItem(id, JSON.stringify(data));
- // Refresh cards
- ipcRenderer.send('refresh-card');
- }
- remove(id) {
- if (localStorage.getItem(id)) {
- const data = JSON.parse(localStorage.getItem(id));
- // Confirm dialog
- ipcRenderer.send('confirm-delete', data.title);
- return new Promise(resolve => {
- ipcRenderer.once('delete-card', (event, confirm) => {
- if (confirm) {
- // Remove from localStorage
- localStorage.removeItem(id);
- // Remove from list
- const list = JSON.parse(localStorage.list);
- list.removeItem(id);
- localStorage.setItem('list', JSON.stringify(list));
- }
- resolve(confirm);
- });
- });
- }
- }
- reset() {
- localStorage.clear();
- this.__load();
- }
- /* --- Private methode --- */
- __load() {
- ipcRenderer.send('load-file-data');
- ipcRenderer.once('file-data-loaded', (event, data) => {
- for(const key in data) {
- localStorage.setItem(key, JSON.stringify(data[key]));
- }
- });
- }
- __uniqid() {
- return '_' + Math.random().toString(36).substr(2, 9);
- }
- }
- module.exports = new DataService();
|