feat(api): implement invoke

This commit is contained in:
Il Harper 2024-03-05 21:31:45 +08:00
parent 6b473e4874
commit 15a3b600c5
No known key found for this signature in database
GPG Key ID: 4B71FCA698E7E8EC
2 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,12 @@
import type { Group, Profile, RedIpcData, RedIpcEvent } from '@chronocat/red'
export const requestMethodMap: Record<string, string> = {}
export const requestCallbackMap: Record<
string,
(this: RedIpcEvent, detail: RedIpcData) => void
> = {}
export const groupMap: Record<string, Group> = {}
export const roleMap: Record<string, Record<string, number>> = {}
export const friendMap: Record<string, Profile> = {}
export const richMediaDownloadMap: Record<string, (path: string) => void> = {}

View File

@ -0,0 +1,61 @@
// https://github.com/import-js/eslint-plugin-import/issues/2802
// eslint-disable-next-line import/no-unresolved
import { ipcMain } from 'electron'
import { requestCallbackMap } from './globalVars'
import type { NtApi } from './types'
export const invoke = async (
channel: string,
eventName: unknown,
...args: unknown[]
) => {
const uuid = generateUUID()
const result = await Promise.race([
new Promise((_, reject) => setTimeout(() => reject(), 10000)),
new Promise((resolve) => {
requestCallbackMap[uuid] = resolve
ipcMain.emit(
channel,
{
sender: {
send: (...args: unknown[]) => {
resolve(args)
},
},
},
{
type: 'request',
callbackId: uuid,
eventName,
},
args,
)
}),
])
delete requestCallbackMap[uuid]
return result
}
export type Invoke = typeof invoke
export function define<R = undefined, A extends unknown[] = []>(
eventName: string,
method: string,
): NtApi<R, A> {
return (...args: A) =>
invoke('IPC_UP_2', eventName, method, ...args) as Promise<R>
}
const generateUUID = () => {
let d = new Date().getTime()
d += performance.now()
const uuid = 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (d + Math.random() * 16) % 16 | 0
d = Math.floor(d / 16)
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
return uuid
}