Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add debounceRequest function #338

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/components/intent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export class Intent {
ensureClientSyncingCallback: () => Promise<void>;
};
private readyPromise?: Promise<unknown>;
private readonly debouncedRequests = new Map<string, Promise<unknown>>();

/**
* Create an entity which can fulfil the intent of a given user.
Expand Down Expand Up @@ -865,6 +866,31 @@ export class Intent {
}
}

/**
* Debounce a request to the intent
* @param requestKey A unique key name for the request. E.g. "bridge-channel-id"
* @param fnName A function on this object. E.g. "joinRoom"
* @param args Args to pass to the function.
* @returns A object containing the promise and a function to clear the value.
*/
public debounceRequest<T>(requestKey: string, fnName: keyof Intent, ...args: unknown[])
: { promise: Promise<T>, clear?: () => void } {
if (fnName === "debounceRequest") {
throw Error('Cannot debounce this function');
}
const key = `${fnName}:${requestKey}`;
const existing = this.debouncedRequests.get(key);
if (existing) {
return { promise: existing as Promise<T> };
}
const promise = this[fnName](...args);
this.debouncedRequests.set(key, promise);
return {
promise,
clear: () => { this.debouncedRequests.delete(key) }
};
}

// Guard a function which returns a promise which may reject if the user is not
// in the room. If the promise rejects, join the room and retry the function.
private async _joinGuard<T>(roomId: string, promiseFn: () => Promise<T>): Promise<T> {
Expand Down