-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
index.js
86 lines (67 loc) · 1.92 KB
/
index.js
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
import process from 'node:process';
import path from 'node:path';
import {
app,
ipcMain,
shell,
} from 'electron'; // eslint-disable-line import/no-duplicates
import electron from 'electron'; // eslint-disable-line import/no-duplicates
import Conf from 'conf';
let isInitialized = false;
// Set up the `ipcMain` handler for communication between renderer and main process.
const initDataListener = () => {
if (!ipcMain || !app) {
throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
}
const appData = {
defaultCwd: app.getPath('userData'),
appVersion: app.getVersion(),
};
if (isInitialized) {
return appData;
}
ipcMain.on('electron-store-get-data', event => {
event.returnValue = appData;
});
isInitialized = true;
return appData;
};
export default class ElectronStore extends Conf {
constructor(options) {
let defaultCwd;
let appVersion;
// If we are in the renderer process, we communicate with the main process
// to get the required data for the module otherwise, we pull from the main process.
if (process.type === 'renderer') {
const appData = electron.ipcRenderer.sendSync('electron-store-get-data');
if (!appData) {
throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
}
({defaultCwd, appVersion} = appData);
} else if (ipcMain && app) {
({defaultCwd, appVersion} = initDataListener());
}
options = {
name: 'config',
...options,
};
options.projectVersion ||= appVersion;
if (options.cwd) {
options.cwd = path.isAbsolute(options.cwd) ? options.cwd : path.join(defaultCwd, options.cwd);
} else {
options.cwd = defaultCwd;
}
options.configName = options.name;
delete options.name;
super(options);
}
static initRenderer() {
initDataListener();
}
async openInEditor() {
const error = await shell.openPath(this.path);
if (error) {
throw new Error(error);
}
}
}