Skip to content

Commit

Permalink
Make some network calls abortable
Browse files Browse the repository at this point in the history
  • Loading branch information
sisou committed Nov 29, 2024
1 parent 1a02d5f commit bdb8fcc
Showing 1 changed file with 30 additions and 13 deletions.
43 changes: 30 additions & 13 deletions src/lib/NetworkClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,21 +48,25 @@ export class NetworkClient {
);
}

public async getBalance(addresses: string[]) {
const client = await this.client;
const accounts = await client.getAccounts(addresses);
return new Map(accounts.map((account, i) => [addresses[i], account.balance]));
public async getBalance(addresses: string[], options?: Partial<{signal: AbortSignal}>) {
return this.abortable(async () => {
const client = await this.client;
const accounts = await client.getAccounts(addresses);
return new Map(accounts.map((account, i) => [addresses[i], account.balance]));
}, options?.signal);
}

public async getStake(addresses: string[]) {
const client = await this.client;
const accounts = await client.getStakers(addresses);
return new Map(accounts.map((account, i) => [
addresses[i],
account
? account.balance + account.inactiveBalance
: 0,
]));
public async getStake(addresses: string[], options?: Partial<{signal: AbortSignal}>) {
return this.abortable(async () => {
const client = await this.client;
const accounts = await client.getStakers(addresses);
return new Map(accounts.map((account, i) => [
addresses[i],
account
? account.balance + account.inactiveBalance
: 0,
]));
}, options?.signal);
}

public async getHeight() {
Expand Down Expand Up @@ -138,4 +142,17 @@ export class NetworkClient {
default: throw new Error(`${ERROR_INVALID_NETWORK}: ${network}`);
}
}

private abortable<T>(callback: () => Promise<T>, signal?: AbortSignal) {
if (!signal) return callback();

return new Promise<T>((resolve, reject) => {
if (signal.aborted) return reject(new Error('aborted'));
const abortListener = () => reject(new Error('aborted'));
signal.addEventListener('abort', abortListener, { once: true });
callback().then(resolve, reject).finally(() => {
signal.removeEventListener('abort', abortListener);
});
});
}
}

0 comments on commit bdb8fcc

Please sign in to comment.