Skip to content

Commit

Permalink
feat: support returning a Promise from the filter utility function (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
n1ru4l committed Jan 5, 2023
1 parent 97f962d commit fe4a2ac
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
9 changes: 9 additions & 0 deletions .changeset/eighty-pigs-know.md
@@ -0,0 +1,9 @@
---
'@graphql-yoga/subscription': minor
---

Support returning a `Promise` from the `filter` utility function.

```ts
const applyFilter = filter((value) => Promise.resolve(value > 3))
```
16 changes: 15 additions & 1 deletion packages/subscription/src/operator/filter.spec.ts
Expand Up @@ -12,7 +12,6 @@ async function collectAsyncIterableValues<TType>(

describe('filter', () => {
it('filters source stream', async () => {
// eslint-disable-next-line @typescript-eslint/require-await
async function* source() {
yield 1
yield 2
Expand All @@ -26,4 +25,19 @@ describe('filter', () => {

expect(result).toEqual([1, 2, 1])
})

it('async filter is supported', async () => {
async function* source() {
yield 1
yield 2
yield 3
yield 1
}

const filterFn = (value: number) => Promise.resolve(value < 3)
const stream = filter(filterFn)(source())
const result = await collectAsyncIterableValues(stream)

expect(result).toEqual([1, 2, 1])
})
})
6 changes: 3 additions & 3 deletions packages/subscription/src/operator/filter.ts
Expand Up @@ -7,9 +7,9 @@ export function filter<T, U extends T>(
filter: (input: T) => input is U,
): (source: AsyncIterable<T>) => Repeater<U, void, unknown>
export function filter<T>(
filter: (input: T) => boolean,
filter: (input: T) => Promise<boolean> | boolean,
): (source: AsyncIterable<T>) => Repeater<T, void, unknown>
export function filter(filter: (value: unknown) => boolean) {
export function filter(filter: (value: unknown) => Promise<boolean> | boolean) {
return (source: AsyncIterable<unknown>) =>
new Repeater(async (push, stop) => {
const iterable = source[Symbol.asyncIterator]()
Expand All @@ -19,7 +19,7 @@ export function filter(filter: (value: unknown) => boolean) {

let latest: IteratorResult<unknown>
while ((latest = await iterable.next()).done === false) {
if (filter(latest.value)) {
if (await filter(latest.value)) {
await push(latest.value)
}
}
Expand Down

0 comments on commit fe4a2ac

Please sign in to comment.