Browse Source

数据持久化。

skyffire 1 year ago
parent
commit
9fa9c7d014
4 changed files with 71 additions and 12 deletions
  1. 47 11
      example/main.js
  2. 1 1
      example/package.json
  3. 20 0
      example/src/App.js
  4. 3 0
      example/src/preload.js

+ 47 - 11
example/main.js

@@ -11,6 +11,8 @@ let memoryCache = {};
 
 const loginFilePath = path.join(app.getPath('userData'), 'loginSession.json');
 const symbolFilePath = path.join(app.getPath('userData'), 'symbolSession.json');
+const dbBasePath = path.join(app.getPath('userData'))
+
 function readData(filePath) {
   try {
     if (fs.existsSync(filePath)) {
@@ -102,6 +104,9 @@ function createWindow() {
   console.log(Object.keys(memoryCache))
 }
 
+let memoryDbData = []
+let memoryDbPath = undefined
+
 app.whenReady().then(() => {
   ipcMain.handle('get-login-info-data', () => {
     return readData(loginFilePath);
@@ -118,6 +123,32 @@ app.whenReady().then(() => {
   ipcMain.handle('set-symbol-data', (event, newData) => {
     writeData(symbolFilePath, newData);
   });
+
+  ipcMain.handle('set-db-data', (event, dataList, symbol) => {
+    const finalPath = path.join(dbBasePath, `${symbol}.json`)
+    writeData(finalPath, dataList)
+
+    console.log(`Local db is set. ${finalPath}`)
+  })
+
+  ipcMain.handle('get-db-data', (event, symbol) => {
+    const finalPath = path.join(dbBasePath, `${symbol}.json`)
+    const rst = readData(finalPath)
+
+    if (JSON.stringify(rst) === '{}') {
+      console.log(`No local db is found:${finalPath}`)
+      return []
+    } else {
+      console.log(`Local db is found:${finalPath}, length: ${rst.length}`)
+      return rst
+    }
+  })
+
+  ipcMain.handle('flush-memory-db-data', (event, data, symbol) => {
+    memoryDbData = data
+    if (!memoryDbPath) memoryDbPath = path.join(dbBasePath, `${symbol}.json`)
+    // console.log(`Memory db is flush。length: ${memoryDbData.length}, symbol: ${symbol}`)
+  })
 });
 
 app.on('ready', () => {
@@ -130,36 +161,36 @@ app.on('ready', () => {
     if (isDev && relativePath.indexOf('react-stock-heatmap/example') !== -1) {
       relativePath = relativePath.split('react-stock-heatmap/example')[1]
     }
-    console.log(relativePath)
+    // console.log(relativePath)
 
     if (memoryCache[relativePath]) {
       let sanitizedRelativePath = relativePath.replace('app.asar', 'app_asar'); // 避免路径中包含 app.asar
-      console.log(app.getPath('temp'), sanitizedRelativePath)
+      // console.log(app.getPath('temp'), sanitizedRelativePath)
       const tempFilePath = path.join(app.getPath('temp'), sanitizedRelativePath);
-      console.log(`Temp File Path: ${tempFilePath}`);
+      // console.log(`Temp File Path: ${tempFilePath}`);
 
       const tempDir = path.dirname(tempFilePath);
-      console.log(`Temp Directory Path: ${tempDir}`);
+      // console.log(`Temp Directory Path: ${tempDir}`);
 
       // 确保临时目录路径存在
       if (!fs.existsSync(tempDir)) {
-        console.log(`Creating directory: ${tempDir}`);
+        // console.log(`Creating directory: ${tempDir}`);
         fs.mkdirSync(tempDir, { recursive: true });
-        console.log(`Directory created: ${tempDir}`);
+        // console.log(`Directory created: ${tempDir}`);
       } else {
-        console.log(`Directory already exists: ${tempDir}`);
+        // console.log(`Directory already exists: ${tempDir}`);
       }
 
       // 确保目录存在后再写入文件
       if (fs.existsSync(tempDir)) {
-        console.log(`Writing file: ${tempFilePath}`);
+        // console.log(`Writing file: ${tempFilePath}`);
         fs.writeFileSync(tempFilePath, memoryCache[relativePath]);
-        console.log(`File written: ${tempFilePath}`);
+        // console.log(`File written: ${tempFilePath}`);
 
-        console.log(`Intercepting request for: ${relativePath}, redirectURL: ${tempFilePath}`);
+        // console.log(`Intercepting request for: ${relativePath}, redirectURL: ${tempFilePath}`);
         callback({ cancel: false, redirectURL: tempFilePath });
       } else {
-        console.error(`Directory does not exist after creation attempt: ${tempDir}`);
+        // console.error(`Directory does not exist after creation attempt: ${tempDir}`);
         callback({ cancel: false });
       }
     } else {
@@ -171,6 +202,11 @@ app.on('ready', () => {
 });
 
 app.on('window-all-closed', () => {
+  if (memoryDbData.length > 0 && memoryDbPath) {
+    writeData(memoryDbPath, memoryDbData);
+    console.log(`Exit saved db is ok. length: ${memoryDbData.length}, path:${memoryDbPath}`)
+  }
+
   if (process.platform !== 'darwin') {
     app.quit();
   }

+ 1 - 1
example/package.json

@@ -1,7 +1,7 @@
 {
   "name": "heatmap",
   "homepage": ".",
-  "version": "1.1.1",
+  "version": "1.1.2",
   "private": true,
   "main": "main.js",
   "scripts": {

+ 20 - 0
example/src/App.js

@@ -161,6 +161,7 @@ export default () => {
       let stock = parseStockData(message)
 
       ref.addData(stock)
+      window.electronAPI.flushMemoryDbData(ref.data, symbolInfo.symbol)
 
       if (progressRef.current !== null) {
         progressRef.current.innerHTML = ` 等待数据推送 ${(100 * ref.data.length / ref.windowLength + 1).toFixed(0)}% ...`
@@ -195,6 +196,20 @@ export default () => {
     window.sessionStorage.setItem("_HEATMAP_IS_LOGIN", "1")
   }
 
+  // 保存数据库到本地
+  const saveLocalDb = async () => {
+    const symbolInfo = symbolOptions.find((item)=> item.id === loginSymbol)
+    let ref = heatmapRef.current
+    await window.electronAPI.setDbData(ref.data, symbolInfo.symbol)
+  }
+
+  // 获取本地的数据库
+  const readLocalDb = async () => {
+    const symbolInfo = symbolOptions.find((item)=> item.id === loginSymbol)
+    let ref = heatmapRef.current
+    ref.data = await window.electronAPI.getDbData(symbolInfo.symbol)
+  }
+
   const handleActivation = async ()=>{
     toast.remove();
     const params = {
@@ -210,7 +225,12 @@ export default () => {
         checkStatus()
       },5000)
       setIsActivation(true)
+      await readLocalDb()
       connectWebSocket()
+      // 每20秒存放一次本地数据
+      setInterval(() => {
+        saveLocalDb()
+      }, 20 * 1000)
     }else{
       toast.error(response.data.msg);
     }

+ 3 - 0
example/src/preload.js

@@ -5,4 +5,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
   setLoginInfoData: (data) => ipcRenderer.invoke('set-login-info-data', data),
   getSymbolData: () => ipcRenderer.invoke('get-symbol-data'),
   setSymbolData: (data) => ipcRenderer.invoke('set-symbol-data', data),
+  getDbData: (symbol) => ipcRenderer.invoke('get-db-data', symbol),
+  setDbData: (data, symbol) => ipcRenderer.invoke('set-db-data', data, symbol),
+  flushMemoryDbData: (data, symbol) => ipcRenderer.invoke('flush-memory-db-data', data, symbol),
 });