System to handle IPC communication

This commit is contained in:
Geomitron
2020-02-03 23:24:15 -05:00
parent 95c46cad39
commit a4becd92aa
10 changed files with 150 additions and 22 deletions

View File

@@ -0,0 +1,11 @@
import { IPCHandler } from '../shared/IPCHandler'
import { TestInput } from '../shared/interfaces/test.interface'
export default class TestHandler implements IPCHandler<'test-event-A'> {
event = 'test-event-A' as 'test-event-A'
async handler(data: TestInput) {
await new Promise<void>((resolve) => setTimeout(() => resolve(), 3000))
return `Processed data with value1 = ${data.value1} and value2 + 5 = ${data.value2 + 5}`
}
}

View File

@@ -3,7 +3,7 @@ import * as path from 'path'
import * as url from 'url'
// IPC Handlers
// import { getIPCHandlers } from './src/assets/electron/shared/IPCHandler'
import { getIPCHandlers } from './shared/IPCHandler'
let mainWindow: BrowserWindow
const args = process.argv.slice(1)
@@ -60,7 +60,7 @@ function createBridgeWindow() {
mainWindow.setMenu(null)
// IPC handlers
// getIPCHandlers().map(handler => ipcMain.handle(handler.event, (_event, ...args) => handler.handler(args[0])))
getIPCHandlers().map(handler => ipcMain.handle(handler.event, (_event, ...args) => handler.handler(args[0])))
// Load angular app
mainWindow.loadURL(getLoadUrl())

View File

@@ -0,0 +1,32 @@
import TestHandler from '../ipc/TestHandler.ipc'
import { TestInput } from './interfaces/test.interface'
/**
* To add a new IPC listener:
* 1.) Write input/output interfaces
* 2.) Add the event to IPCEvents
* 3.) Write a class that implements IPCHandler
* 4.) Add the class to getIPCHandlers
*/
export function getIPCHandlers(): IPCHandler<keyof IPCEvents>[] {
return [
new TestHandler()
]
}
export type IPCEvents = {
['test-event-A']: {
input: TestInput
output: string
}
['test-event-B']: {
input: number
output: number
}
}
export interface IPCHandler<E extends keyof IPCEvents> {
event: E
handler(data: IPCEvents[E]['input']): Promise<IPCEvents[E]['output']> | IPCEvents[E]['output']
}

View File

@@ -0,0 +1,4 @@
export interface TestInput {
value1: string
value2: number
}