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

chore: clean up, cancel-poll hook #936

Merged
merged 4 commits into from
Mar 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions packages/client/hmi-client/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,33 +55,40 @@ const NOOP = () => {};
export enum PollerState {
Done = 'done',
Failed = 'failed',
ExceedThreshold = 'ExceedThreshold'
ExceedThreshold = 'ExceedThreshold',
Cancelled = 'Cancelled'
}

// FIXME: need to refine based on actual needs
interface PollResponse<T> {
error: any;
progress: any;
data: T;
}

type PollerCallback<T> = (...args: any[]) => Promise<PollResponse<T>>;

interface PollerResult<T> {
state: PollerState;
data: T | null;
}

export class Poller<T> {
pollingInterval = 2000;

pollingThreshold = 10;

keepGoing = false;

poll: Function = NOOP;
poll: PollerCallback<T> | null;

progressAction: Function = NOOP;

numPolls = 0;

constructor() {
this.poll = null;
}

setInterval(v: number) {
this.pollingInterval = v;
return this;
Expand Down Expand Up @@ -113,10 +120,15 @@ export class Poller<T> {

let response: PollResponse<T> | null = null;

if (!this.poll) throw new Error('Poll callback undefined');

while (this.numPolls < this.pollingThreshold) {
this.numPolls++;
if (!this.keepGoing) {
break;
return {
state: PollerState.Cancelled,
data: null
};
}

try {
Expand Down
23 changes: 23 additions & 0 deletions packages/client/hmi-client/tests/unit/api/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,27 @@ describe('API utilities test', () => {
const result = await poller.start();
expect(result.state).eq('ExceedThreshold');
});

it('polling can be cancelled', async () => {
let c = 0;
const poller = new Poller<number[]>()
.setInterval(1000)
.setThreshold(10)
.setPollAction(async () => {
c++;
if (c <= 99) {
return { data: null, error: null };
}
return { data: [1, 2, 3], error: null };
});

// Cancel between 2nd and 3rd iteration
setTimeout(() => {
poller.stop();
}, 2500);
const result = await poller.start();
expect(result.state).eq('Cancelled');
expect(c).gt(1);
expect(c).lt(4);
});
});