Skip to content

Commit

Permalink
fix: prefetch shouldn't cancel (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
timdeschryver authored Sep 3, 2022
1 parent 813cce9 commit 16c4350
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 38 deletions.
14 changes: 8 additions & 6 deletions rx-query/__tests__/prefetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,40 @@ it('sends a fetch event', () => {
revalidate.pipe(map((v) => ({ trigger: v.trigger, key: v.key }))),
).toBe('(abc)d', {
a: { trigger: 'query-subscribe', key: 'key' },
b: { trigger: 'query-unsubscribe', key: 'key' },
c: { trigger: 'group-unsubscribe', key: 'key' },
b: { trigger: 'group-unsubscribe', key: 'key' },
c: { trigger: 'query-unsubscribe', key: 'key' },
d: { trigger: 'group-remove', key: 'key' },
});
prefetch('key', () => of('result'), { cacheTime: 5 });
});
});


it('sends a fetch event with static params', () => {
const testScheduler = new TestScheduler((a, e) => expect(a).toStrictEqual(e));
testScheduler.run(({ expectObservable }) => {
expectObservable(
revalidate.pipe(map((v) => ({ trigger: v.trigger, key: v.key }))),
).toBe('(abc)d', {
a: { trigger: 'query-subscribe', key: 'key-{"id":1}' },
b: { trigger: 'query-unsubscribe', key: 'key-{"id":1}' },
c: { trigger: 'group-unsubscribe', key: 'key-{"id":1}' },
b: { trigger: 'group-unsubscribe', key: 'key-{"id":1}' },
c: { trigger: 'query-unsubscribe', key: 'key-{"id":1}' },
d: { trigger: 'group-remove', key: 'key-{"id":1}' },
});
prefetch('key', { id: 1 }, () => of('result'), { cacheTime: 5 });
});
});


it('sends a fetch event with Observable params', () => {
const testScheduler = new TestScheduler((a, e) => expect(a).toStrictEqual(e));
testScheduler.run(({ expectObservable }) => {
expectObservable(
revalidate.pipe(map((v) => ({ trigger: v.trigger, key: v.key }))),
).toBe('(abc)d', {
a: { trigger: 'query-subscribe', key: 'key-{"id":1}' },
b: { trigger: 'query-unsubscribe', key: 'key-{"id":1}' },
c: { trigger: 'group-unsubscribe', key: 'key-{"id":1}' },
b: { trigger: 'group-unsubscribe', key: 'key-{"id":1}' },
c: { trigger: 'query-unsubscribe', key: 'key-{"id":1}' },
d: { trigger: 'group-remove', key: 'key-{"id":1}' },
});
prefetch('key', of({ id: 1 }), () => of('result'), { cacheTime: 5 });
Expand Down
4 changes: 0 additions & 4 deletions rx-query/__tests__/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ import {
revalidate,
QueryOutput,
Revalidator,
resetQueryCache,
refreshQuery,
NOOP_MUTATE,
} from '..';

beforeEach(() => {
resetQueryCache();
});

it('first loads then succeeds', async () => {
const values = [];
Expand Down
22 changes: 10 additions & 12 deletions rx-query/cache.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import {
Subject,
of,
scheduled,
asapScheduler,
EMPTY,
timer,
Observable,
GroupedObservable,
queueScheduler,
} from 'rxjs';
import {
scan,
Expand All @@ -20,15 +19,16 @@ import {
filter,
switchMap,
takeUntil,
concatAll,
shareReplay,
startWith,
} from 'rxjs/operators';
import { NOOP_MUTATE, QueryConfig, QueryOutput, Revalidator } from './types';

let cacheKeys: string[] = [];
export const revalidate = new Subject<Revalidator>();

export const queryCache = revalidate.pipe(
observeOn(queueScheduler),
tap((r) => {
if (r.key && r.trigger === 'group-remove') {
cacheKeys = cacheKeys.filter((key) => key !== r.key);
Expand Down Expand Up @@ -90,7 +90,6 @@ export const queryCache = revalidate.pipe(
),
map((group) =>
group.pipe(
observeOn(asapScheduler),
scan(
(subscriptions, revalidator) =>
holdSubscriptionsCount(subscriptions, revalidator),
Expand Down Expand Up @@ -172,8 +171,8 @@ export const queryCache = revalidate.pipe(
'mutate-error': () =>
updateTrigger(groupState, revalidator, queryConfig),
} as {
[handler in Revalidator['trigger']]: () => Observable<Group>;
};
[handler in Revalidator['trigger']]: () => Observable<Group>;
};

const handlers = {
idle: {
Expand Down Expand Up @@ -303,10 +302,10 @@ export const queryCache = revalidate.pipe(
...defaultHandlers,
},
} as {
[status in QueryOutput['status']]: {
[handler in Revalidator['trigger']]: () => Observable<Group>;
[status in QueryOutput['status']]: {
[handler in Revalidator['trigger']]: () => Observable<Group>;
};
};
};

const handler =
handlers[groupState.result.status][revalidator.trigger];
Expand Down Expand Up @@ -450,7 +449,6 @@ function invokeQuery(
group.pipe(
filter(
(r) =>
r.trigger === 'group-unsubscribe' ||
r.trigger === 'group-remove' ||
r.trigger === 'mutate-optimistic',
),
Expand Down Expand Up @@ -492,8 +490,8 @@ function invokeQuery(
subscriptions,
};

return scheduled([of(initial), invoker], asapScheduler).pipe(
concatAll(),
return invoker.pipe(
startWith(initial),
map((r) => {
return {
groupState: r,
Expand Down
6 changes: 3 additions & 3 deletions rx-query/prefetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Observable, of, isObservable } from 'rxjs';
import { take, mergeMap, shareReplay } from 'rxjs/operators';
import { Observable, of, isObservable, asapScheduler } from 'rxjs';
import { take, mergeMap, shareReplay, observeOn } from 'rxjs/operators';
import { query } from './query';
import { QueryConfig } from './types';

Expand All @@ -20,7 +20,7 @@ export function prefetch(key: string, ...inputs: unknown[]): void {
queryParam
.pipe(
mergeMap((parameter) =>
query(key, parameter, inputQuery, queryConfig).pipe(take(1)),
query(key, parameter, inputQuery, queryConfig).pipe(observeOn(asapScheduler), take(1)),
),
)
.subscribe();
Expand Down
3 changes: 0 additions & 3 deletions rx-query/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ import {
startWith,
catchError,
expand,
debounce,
withLatestFrom,
distinctUntilChanged,
finalize,
filter,
mergeAll,
take,
pairwise,
concatMap,
Expand Down Expand Up @@ -163,7 +161,6 @@ export function query(
)
.subscribe({
next: (c) => revalidate.next(c),
complete: () => console.warn('complete'),
});

return queryCache.pipe(
Expand Down
31 changes: 21 additions & 10 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';

import { query, prefetch } from '../../rx-query';
import { query, prefetch, refreshQuery } from '../../rx-query';

import { RickAndMortyService } from './rickandmorty.service';

Expand Down Expand Up @@ -66,15 +66,26 @@ export class AppComponent implements OnInit, OnDestroy {
},
);

prefetch(
'character',
5,
(characterId: number) =>
this.rickAndMortyService.getCharacter(characterId),
{
staleTime: 50000,
},
);
Array.from({ length: 3 }).forEach((_, i) => {
prefetch(
'character',
i + 1,
(characterId: number) =>
this.rickAndMortyService.getCharacter(characterId),
{
staleTime: 50000,
},
);
})


setTimeout(() => {
Array.from({ length: 3 }).forEach((_, i) => {
refreshQuery(
'character-' + (i + 1),
);
})
}, 1_000);
}

ngOnDestroy(): void {
Expand Down
4 changes: 4 additions & 0 deletions src/setup-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import 'jest-preset-angular/setup-jest';
import '@testing-library/jest-dom';
import { server } from './mocks/server';
import { resetQueryCache } from '../rx-query';

beforeAll(() => server.listen());
beforeEach(() => {
resetQueryCache();
});
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

0 comments on commit 16c4350

Please sign in to comment.