-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(filter): add a filtering data source function
- Loading branch information
Showing
3 changed files
with
74 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import { DataSource, ResultWithCursor } from './index'; | ||
|
||
// For some data sources, local filtering is all that is possible, but it can be helpful to treat it | ||
// like a paged data source. SO, we will filter results after fetching them and then "top up" the datasource | ||
// with the next page of results if necessary. Suboptimal - to be clear. | ||
export function withFilter<T extends ResultWithCursor>(datasource: DataSource<T>, filter: (result: T) => boolean): DataSource<T> { | ||
return { | ||
async getResults(cursor: string | undefined, forward: boolean, limit: number) { | ||
const results: T[] = []; | ||
do { | ||
// TODO we maybe should optimize the fetch size more | ||
const nextResults = await datasource.getResults(results[results.length - 1]?.cursor || cursor, forward, limit); | ||
results.push(...nextResults.results.filter(filter)); | ||
if (nextResults.results.length < limit) { | ||
// Didn't get the required number of elements, must be the end | ||
break; | ||
} | ||
} while (results.length < limit); | ||
// Can't give a total count | ||
return { results: results.slice(0, limit) }; | ||
}, | ||
sortKey: datasource.sortKey, | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export * from './FilteredDataSource'; | ||
export * from './one-shot'; | ||
export * from './stateful'; | ||
export * from './types'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters