Better way to do "quick save" in electron


#1

So I have implemented a “quick” save for my electron app. There has to be a better way to achieve what I am doing.

The MessageBox will always be triggered on a save as command. If the user selects save (Ctrl+S), I’m basically keeping a variable to hold if a file has been loaded from the file system or not. If a file has been loaded I take the array from fs and convert into a string and use that as the filename for the quick save.

If no file has been uploaded, this means my gantt area is clear and the SaveDialog box will be triggered since this isn’t a loaded file. A little code to further explain. Before the quicksave function the filename is either undefined or a string from the fs array and stored in quickSaveFilename.

    // dirty quicksave
    const quickSave = () => {
      let saveData = gantt.serialize();
      saveData = JSON.stringify(saveData, null, '\t');
      if (quickSaveFileName === undefined) {
        dialog.showSaveDialog(
          {
            defaultPath: `C:\\Users\\${process.env.USERNAME}\\Documents\\`,
            filters: [
              {
                name: 'json',
                extensions: ['json'],
              },
            ],
          },
          (filename) => {
            if (filename === undefined) {
              return;
            }
            fs.writeFile(filename, content, (error) => {
              if (error) {
                dialog.showErrorBox(
                  'Save Failed',
                  `An error occured saving the file ${error.message}`,
                );
                return;
              }
              dialog.showMessageBox({
                type: 'none',
                title: 'Ganttron',
                message: 'The chart was successfully saved',
                buttons: ['OK'],
              });
            });
          });
      } else {
        fs.writeFile(quickSaveFileName, saveData, (error) => {
          if (error) {
            dialog.showErrorBox(
              'Save Failed',
              `An error occured saving the file ${error.message}`,
            );
          }
          dialog.showMessageBox({
            type: 'none',
            title: 'Ganttron',
            message: 'The chart was successfully saved',
            buttons: ['OK'],
          });
        });
      }
    };

Is there a more efficient way of doing this in electron?