/
syncMain.ts
45 lines (37 loc) · 1.57 KB
/
syncMain.ts
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
import { ipcMain, webContents } from 'electron'
import { Action, applyMiddleware, Middleware, StoreCreator, StoreEnhancer } from 'redux'
import { freeze, preventDoubleInitialization, stopForwarding, validateAction } from './utils'
const middleware: Middleware = (store) => {
ipcMain.handle('electron-redux.FETCH_STATE', async () => {
// Stringify the current state, and freeze it to preserve certain types
// that you might want to use in your state, but aren't JSON serializable
// by default.
return JSON.stringify(store.getState(), freeze)
})
// When receiving an action from a renderer
ipcMain.on('electron-redux.ACTION', (event, action: Action) => {
const localAction = stopForwarding(action)
store.dispatch(localAction)
// Forward it to all of the other renderers
webContents.getAllWebContents().forEach((contents) => {
// Ignore the renderer that sent the action
if (contents.id !== event.sender.id) {
contents.send('electron-redux.ACTION', localAction)
}
})
})
return (next) => (action) => {
if (validateAction(action)) {
webContents.getAllWebContents().forEach((contents) => {
contents.send('electron-redux.ACTION', action)
})
}
return next(action)
}
}
export const syncMain: StoreEnhancer = (createStore: StoreCreator) => {
preventDoubleInitialization()
return (reducer, state) => {
return createStore(reducer, state, applyMiddleware(middleware))
}
}