Skip to content

Commit

Permalink
feat(ipcman): support filter()
Browse files Browse the repository at this point in the history
  • Loading branch information
ilharp committed Mar 3, 2024
1 parent caba523 commit 8d64692
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions packages/ipcman/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type Awaitable<T> = T | Promise<T>

export interface IpcManConfig<IpcArgs extends unknown[] = unknown[]> {
handler: (data: IpcManData) => Awaitable<unknown>
filter?: (data: IpcManData) => boolean | Promise<boolean>
getId?: (p: IpcArgs) => string | undefined
getMethod?: (p: IpcArgs) => string | undefined
}
Expand All @@ -84,6 +85,14 @@ export interface IpcManContext {
export const ipcMan = <IpcArgs extends unknown[] = unknown[]>(
config: IpcManConfig<IpcArgs>,
): IpcManContext => {
const handleData = async (data: IpcManData) => {
if (!config.filter) {
config.handler(data)
return
}
if (await config.filter(data)) config.handler(data)
}

const senderExcludeSymbol: unique symbol = Symbol()

let iHandle = 0
Expand All @@ -105,15 +114,15 @@ export const ipcMan = <IpcArgs extends unknown[] = unknown[]>(

const id = config.getId?.(e as IpcArgs)
if (id)
config.handler({
void handleData({
type: 'wrapped-response',
channel,
method: config.getMethod?.(e as IpcArgs),
args: e,
id,
})
else
config.handler({
void handleData({
type: 'event',
channel,
method: config.getMethod?.(e as IpcArgs),
Expand All @@ -126,15 +135,15 @@ export const ipcMan = <IpcArgs extends unknown[] = unknown[]>(

const id = config.getId?.(p)
if (id)
config.handler({
void handleData({
type: 'wrapped-request',
channel: eventName as string,
method: config.getMethod?.(p),
args: p,
id,
})
else
config.handler({
void handleData({
type: 'request',
channel: eventName as string,
method: config.getMethod?.(p),
Expand All @@ -149,7 +158,7 @@ export const ipcMan = <IpcArgs extends unknown[] = unknown[]>(
const wrappedFn = async (event: IpcMainInvokeEvent, ...args: unknown[]) => {
const id = `IPCMAN_HANDLE_${iHandle++}`

config.handler({
void handleData({
type: 'handle-request',
channel: method,
method: config.getMethod?.(args as IpcArgs),
Expand All @@ -159,7 +168,7 @@ export const ipcMan = <IpcArgs extends unknown[] = unknown[]>(

const result = (await Promise.resolve(fn(event, ...args))) as unknown

config.handler({
void handleData({
type: 'handle-response',
channel: method,
method: config.getMethod?.(args as IpcArgs),
Expand Down

0 comments on commit 8d64692

Please sign in to comment.