-
Notifications
You must be signed in to change notification settings - Fork 12
/
electron.transport.ts
73 lines (62 loc) · 2.26 KB
/
electron.transport.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
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
import type { CustomTransportStrategy, MessageHandler } from '@nestjs/microservices'
import type { IpcContext, IpcOptions } from './interfaces'
import { Logger } from '@nestjs/common'
import { Server } from '@nestjs/microservices'
import { isObservable, lastValueFrom } from 'rxjs'
import { ChannelMaps } from './transport'
import { isElectron, linkPathAndChannel } from './utils'
import './nest.hacker'
export class ElectronIpcTransport extends Server implements CustomTransportStrategy {
protected readonly logger: Logger
constructor(name: string = ElectronIpcTransport.name) {
super()
this.logger = new Logger(name)
}
listen(callback: () => void): any {
if (isElectron) {
const { ipcMain } = require('electron')
ChannelMaps.forEach(({ target, channel, opts }, channelId) => {
const path = Reflect.getMetadata('path', target.constructor)
const channelNames = linkPathAndChannel(channel, path)
const handler = this.getHandlers().get(channelId)
if (!handler) {
const errMsg = `No handler for message channel "${channelNames[0]}"`
this.logger.error(errMsg)
throw new Error(errMsg)
}
for (const ch of channelNames) {
if (handler.isEventHandler)
ipcMain.on(ch, this.applyHandler(handler, ch, opts))
else
ipcMain.handle(ch, this.applyHandler(handler, ch, opts))
}
})
}
callback()
}
private applyHandler(handler: MessageHandler, channel: string, opts: IpcOptions = {}) {
return async (...args) => {
try {
const { noLog } = opts
if (!noLog) {
if (!handler.isEventHandler)
this.logger.log(`[IPC] Process message ${channel}`)
else
this.logger.log(`[IPC] Process event ${channel}`)
}
const [ipcMainEventObject, ...payload] = args
const data = payload.length === 0 ? undefined : payload.length === 1 ? payload[0] : payload
const ctx: IpcContext = { ipcEvt: ipcMainEventObject }
const res = await handler(data, ctx)
return isObservable(res)
? await lastValueFrom(res)
: res
}
catch (error) {
throw new Error(error.message ?? error)
}
}
}
close(): any {
}
}