typicode / lowdb

Simple and fast JSON database
MIT License
21.35k stars 918 forks source link

How lowdb communicate between IPC and RPC in Electron ? #504

Closed Proladon closed 2 years ago

Proladon commented 2 years ago

Communicate with ipcMain and ipcRenderer will lost the Low instance turn into normal object :

// ipcMain
ipcMain.handle('Database-Connect', async (e, filePath: string) => {
  try {
    const db: Low = new Low(new JSONFile(filePath))
    await db.read()
    console.log( typeof db) // Low
    return db
  } 
  catch (error) {
    return error
  }
})
// ipcRenderer
connect(filePath: string) {
  const res = ipcRenderer.invoke('Database-Connect', filePath: string)
  return res
}
// Renderer Proccess
const connectDB = async () => {
  const db = await ConnectLowDB( filePath: string )
  console.log( typeof db) // object <- turn into object
}

so I'v to re new a Low instance in everytimes like :

ipcMain.handle('Database-Write', async (e, { dbFilePath, key, data }) => {
  try {
    const database: Low = new Low(new JSONFile(dbFilePath)) // new Low instance
    database.data ||= {
      mainFolder: '',
    }

    await database.read()
    database.data[key] = data
    await database.write()
    return ['done', null]
  } 
  catch (error) {
    return [null, error]
  }
})

Is there have a better ways?

ste163 commented 2 years ago

Not sure if it's the best way, but it worked well enough:

The renderer shouldn't know anything about lowdb. The renderer should be passing JSON payloads over ipc to the main process, and then the main process saves that data using the lowdb instance.

One of my projects using this: https://github.com/ste163/vislit-prototype/blob/main/src/main/background.js

Proladon commented 2 years ago

Not sure if it's the best way, but it worked well enough:

The renderer shouldn't know anything about lowdb. The renderer should be passing JSON payloads over ipc to the main process, and then the main process saves that data using the lowdb instance.

One of my projects using this: https://github.com/ste163/vislit-prototype/blob/main/src/main/background.js

nc job 👍 actually I just don't know how to keep lowdb instance in main process, that I can reuse it lol I'v already understood after read ur source code, thx

but I still wanna to know is there have others way, so I'm gonna keep this issues opening

typicode commented 2 years ago

Going to close as there's not much activity and it's more a question than an issue. Thanks for sharing @ste163