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

Use standard Typescript AsyncIterator types #1745

Merged
merged 3 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
37 changes: 13 additions & 24 deletions src/autoPagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@ import {callbackifyPromiseWithTimeout, getDataFromArgs} from './utils.js';
type PromiseCache = {
currentPromise: Promise<any> | undefined | null;
};
type IterationResult<T> =
| {
done: false;
value: T;
}
| {done: true; value?: undefined};
type IterationDoneCallback = () => void;
type IterationItemCallback<T> = (
item: T,
Expand All @@ -31,18 +25,15 @@ type AutoPagingToArray<T> = (
type AutoPaginationMethods<T> = {
autoPagingEach: AutoPagingEach<T>;
autoPagingToArray: AutoPagingToArray<T>;
next: () => Promise<IterationResult<T>>;
next: () => Promise<IteratorResult<T>>;
return: () => void;
};
interface IStripeIterator<T> {
next: () => Promise<IterationResult<T>>;
}
type PageResult<T> = {
data: Array<T>;
has_more: boolean;
next_page: string | null;
};
class StripeIterator<T> implements IStripeIterator<T> {
class StripeIterator<T> implements AsyncIterator<T> {
private index: number;
private pagePromise: Promise<PageResult<T>>;
private promiseCache: PromiseCache;
Expand All @@ -63,7 +54,7 @@ class StripeIterator<T> implements IStripeIterator<T> {
this.stripeResource = stripeResource;
}

async iterate(pageResult: PageResult<T>): Promise<IterationResult<T>> {
async iterate(pageResult: PageResult<T>): Promise<IteratorResult<T>> {
if (
!(
pageResult &&
Expand Down Expand Up @@ -92,21 +83,19 @@ class StripeIterator<T> implements IStripeIterator<T> {
const nextPageResult = await this.pagePromise;
return this.iterate(nextPageResult);
}
// eslint-disable-next-line no-warning-comments
// TODO (next major) stop returning explicit undefined
return {value: undefined, done: true};
return {done: true, value: undefined};
}

/** @abstract */
getNextPage(_pageResult: PageResult<T>): Promise<PageResult<T>> {
throw new Error('Unimplemented');
}

private async _next(): Promise<IterationResult<T>> {
private async _next(): Promise<IteratorResult<T>> {
return this.iterate(await this.pagePromise);
}

next(): Promise<IterationResult<T>> {
next(): Promise<IteratorResult<T>> {
/**
* If a user calls `.next()` multiple times in parallel,
* return the same result until something has resolved
Expand All @@ -116,7 +105,7 @@ class StripeIterator<T> implements IStripeIterator<T> {
return this.promiseCache.currentPromise;
}

const nextPromise = (async (): Promise<IterationResult<T>> => {
const nextPromise = (async (): Promise<IteratorResult<T>> => {
const ret = await this._next();
this.promiseCache.currentPromise = null;
return ret;
Expand Down Expand Up @@ -174,9 +163,9 @@ export const makeAutoPaginationMethods = <
};

const makeAutoPaginationMethodsFromIterator = <T>(
iterator: IStripeIterator<T>
iterator: AsyncIterator<T>
): AutoPaginationMethods<T> => {
const autoPagingEach = makeAutoPagingEach((...args) =>
const autoPagingEach = makeAutoPagingEach<T>((...args) =>
iterator.next(...args)
);
const autoPagingToArray = makeAutoPagingToArray(autoPagingEach);
Expand Down Expand Up @@ -286,7 +275,7 @@ function getLastId<T extends {id: string}>(
}

function makeAutoPagingEach<T>(
asyncIteratorNext: () => Promise<IterationResult<T>>
asyncIteratorNext: () => Promise<IteratorResult<T>>
): AutoPagingEach<T> {
return function autoPagingEach(/* onItem?, onDone? */): Promise<void> {
const args = [].slice.call(arguments);
Expand Down Expand Up @@ -342,12 +331,12 @@ function makeAutoPagingToArray<T>(
}

function wrapAsyncIteratorWithCallback<T>(
asyncIteratorNext: () => Promise<IterationResult<T>>,
asyncIteratorNext: () => Promise<IteratorResult<T>>,
onItem: IterationItemCallback<T>
): Promise<void> {
return new Promise<void>((resolve, reject) => {
function handleIteration(
iterResult: IterationResult<T>
iterResult: IteratorResult<T>
): Promise<any> | void {
if (iterResult.done) {
resolve();
Expand All @@ -362,7 +351,7 @@ function wrapAsyncIteratorWithCallback<T>(
onItem(item, next);
}).then((shouldContinue) => {
if (shouldContinue === false) {
return handleIteration({done: true});
return handleIteration({done: true, value: undefined});
richardm-stripe marked this conversation as resolved.
Show resolved Hide resolved
} else {
return asyncIteratorNext().then(handleIteration);
}
Expand Down
19 changes: 19 additions & 0 deletions test/autoPagination.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,25 @@ describe('auto pagination', () => {
})
).to.eventually.deep.equal(OBJECT_IDS.slice(0, LIMIT));
});
it('next() returns appropriately-shaped iterator results', async () => {
const {paginator} = mockPaginationV1List([['a', 'b'], ['c']], {});
expect(await paginator.next()).to.deep.equal({
value: {id: 'a'},
done: false,
});
expect(await paginator.next()).to.deep.equal({
value: {id: 'b'},
done: false,
});
expect(await paginator.next()).to.deep.equal({
value: {id: 'c'},
done: false,
});
expect(await paginator.next()).to.deep.equal({
done: true,
value: undefined,
});
});

it('lets you ignore the second arg and `return false` to break', () => {
const {paginator} = mockPaginationV1List(ID_PAGES, {});
Expand Down