mirror of
https://github.com/chrononeko/chronocat.git
synced 2024-11-25 09:37:35 +00:00
feat(api): implement invoke
This commit is contained in:
parent
6b473e4874
commit
15a3b600c5
12
packages/engine-chronocat-api/src/globalVars.ts
Normal file
12
packages/engine-chronocat-api/src/globalVars.ts
Normal 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> = {}
|
61
packages/engine-chronocat-api/src/invoke.ts
Normal file
61
packages/engine-chronocat-api/src/invoke.ts
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user