data.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. const {ipcRenderer} = require('electron');
  2. class DataService {
  3. constructor() {
  4. // Load data from files
  5. if (!localStorage.list) {
  6. this.__load();
  7. }
  8. }
  9. get data() {
  10. const result = [];
  11. const list = JSON.parse(localStorage.list);
  12. for (const element of list) {
  13. result.push(JSON.parse(localStorage.getItem(element)));
  14. }
  15. return result;
  16. }
  17. getById(id) {
  18. const list = JSON.parse(localStorage.list);
  19. if (list.indexOf(id) !== -1) {
  20. return JSON.parse(localStorage.getItem(id));
  21. }
  22. return null;
  23. }
  24. add(id, title, content) {
  25. // If no id (param id = title and param title = content)
  26. if (!content) {
  27. content = title;
  28. title = id;
  29. // Generate id
  30. id = this.__uniqid();
  31. }
  32. // Add in list
  33. const list = JSON.parse(localStorage.list);
  34. list.push(id);
  35. localStorage.setItem('list', JSON.stringify(list));
  36. // Add data
  37. this.update(id, title, content);
  38. }
  39. update(id, title, content) {
  40. // Set object
  41. const data = {
  42. id: id,
  43. title: title,
  44. content: content
  45. }
  46. // Save
  47. localStorage.setItem(id, JSON.stringify(data));
  48. // Refresh cards
  49. ipcRenderer.send('refresh-card');
  50. }
  51. remove(id) {
  52. if (localStorage.getItem(id)) {
  53. const data = JSON.parse(localStorage.getItem(id));
  54. // Confirm dialog
  55. ipcRenderer.send('confirm-delete', data.title);
  56. return new Promise(resolve => {
  57. ipcRenderer.once('delete-card', (event, confirm) => {
  58. if (confirm) {
  59. // Remove from localStorage
  60. localStorage.removeItem(id);
  61. // Remove from list
  62. const list = JSON.parse(localStorage.list);
  63. list.removeItem(id);
  64. localStorage.setItem('list', JSON.stringify(list));
  65. }
  66. resolve(confirm);
  67. });
  68. });
  69. }
  70. }
  71. reset() {
  72. localStorage.clear();
  73. this.__load();
  74. }
  75. /* --- Private methode --- */
  76. __load() {
  77. ipcRenderer.send('load-file-data');
  78. ipcRenderer.once('file-data-loaded', (event, data) => {
  79. for(const key in data) {
  80. localStorage.setItem(key, JSON.stringify(data[key]));
  81. }
  82. });
  83. }
  84. __uniqid() {
  85. return '_' + Math.random().toString(36).substr(2, 9);
  86. }
  87. }
  88. module.exports = new DataService();