feat(companion): add waitForEvent runtime helper
This commit is contained in:
@@ -43,6 +43,7 @@ export interface CompanionRuntimeClientOptions {
|
||||
|
||||
export type CompanionEventHandler = (event: string, data: unknown) => void;
|
||||
export type CompanionTypedEventHandler<TData = unknown> = (data: TData) => void;
|
||||
export type CompanionEventPredicate<TData = unknown> = (data: TData) => boolean;
|
||||
|
||||
export interface RegisterNodeInput {
|
||||
nodeId: string;
|
||||
@@ -365,6 +366,42 @@ export class CompanionRuntimeClient {
|
||||
});
|
||||
}
|
||||
|
||||
waitForEvent<TData = unknown>(
|
||||
eventName: string,
|
||||
options?: {
|
||||
timeoutMs?: number;
|
||||
predicate?: CompanionEventPredicate<TData>;
|
||||
},
|
||||
): Promise<TData> {
|
||||
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
|
||||
const predicate = options?.predicate;
|
||||
|
||||
return new Promise<TData>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const unsubscribe = this.subscribeEvent<TData>(eventName, (data) => {
|
||||
if (predicate && !predicate(data)) {
|
||||
return;
|
||||
}
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
unsubscribe();
|
||||
resolve(data);
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
unsubscribe();
|
||||
reject(new Error(`Timed out waiting for event ${eventName}`));
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async call<T>(method: string, params?: Record<string, unknown>): Promise<T> {
|
||||
if (!this.connected) {
|
||||
if (!this.autoConnect) {
|
||||
|
||||
Reference in New Issue
Block a user